SpringMVC jackson的一个小坑

这是我写的第一篇博客,所以表达的可能很差。

在使用微信jsapi时,需要得到一个jsapi_ticket,而要得到jsapi_ticket,必须先得到access_token。项目框架为SpringMVC,SpringMVC使用的json工具为jackson,之前对这个json工具不是很熟,所以就碰到了这个小坑。

拿access_token时,因为access_token为字符串,所以我直接使用jsonNode.get("access_token").toString();然后拼接成url去拿jsapi_ticket,可结果总是错误的,debug一下吧,发现url中,xxxx?access_token="abcdefghijkl",原来问题在这里;正确的应该是xxxx?access_token=abcdefghijkl;

原因分析:

jsonNode.get("access_token")的结果是一个jsonNode,toString()方法只是把转成一个开发者可读表示法;应该用jsonNode.get("access_token").asText(),这个才是拿到节点容器中的值。


例如

public static void main(String[] args) throws Exception{
        String s = "{\"name\":\"张三\"}";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jNode = mapper.readTree(s);
        System.out.println(jNode.get("name").asText());
        System.out.println(jNode.get("name").toString());
    }

打印结果:

张三

"张三"

第一个是2个长度的字符串

第二个是4个长度的字符串


看源码:

/**
     * Method that will return a valid String representation of
     * the container value, if the node is a value node
     * (method {@link #isValueNode} returns true),
     * otherwise empty String.
     */
    public abstract String asText();


/**
     * Method that will produce developer-readable representation of the
     * node; which may <b>or may not</b> be as valid JSON.
     * If you want valid JSON output (or output formatted using one of
     * other Jackson supported data formats) make sure to use
     * {@link ObjectMapper} or {@link ObjectWriter} to serialize an
     * instance, for example:
     *<pre>
     *   String json = objectMapper.writeValueAsString(rootNode);
     *</pre>
     *<p>
     * Note: method defined as abstract to ensure all implementation
     * classes explicitly implement method, instead of relying
     * on {@link Object#toString()} definition.
     */
    @Override
    public abstract String toString();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值