这是我写的第一篇博客,所以表达的可能很差。
在使用微信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();