JSONObject如何实现按put顺序排放与输出
更新:HHH   时间:2023-1-7


这篇文章主要为大家展示了“JSONObject如何实现按put顺序排放与输出”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“JSONObject如何实现按put顺序排放与输出”这篇文章吧。

JSONObject按put顺序排放与输出

JSONObject put数据之后,排序会发生变化

例如

JSONObject object=new JSONObject();  
object.put("aaa",111);  
object.put("bbb",222);  
object.put("ccc",333); 
object.put("ddd",444);

输出结果可能为

{"aaa":111,"ddd":444,"ccc":333,"bbb":222}

因为JsonObject内部是用Hashmap来存储的,所以输出是按key的排序来的,如果要让JsonObject按固定顺序(put的顺序)排列,可以修改JsonObject的定义HashMap改为LinkedHashMap。

public JSONObject() {  
        this.map = new LinkedHashMap();  //new HashMap();  
}

即定义JsonObject可以这样:JSONObject jsonObj =new JSONObject(new LinkedHashMap());

JSONObject object=new JSONObject(new LinkedHashMap());
object.put("aaa",111);  
object.put("bbb",222);  
object.put("ccc",333); 
object.put("ddd",444);

再次输出就会按顺序排了。

不知道大家想要的结果得到了没,反正我想要的结果已经得到。不解释,看下图--------->

JSONObject.put 的坑

net.sf.json.JSONObject
String timelineContent=一个json
Json.put("timelineContent",timelineContent);

此时框架会自动将String类型的timelineContent当Json put进去。。。

然后因为接口要求String不要JsonObject,就报

{"errorCode":-1,"errorMessage":"Internal Server Error","exceptionClassName":"org.springframework.http.converter.HttpMessageNotReadableException","exceptionMessage":"JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 397] (through reference chain: java.util.ArrayList[0]->com.homethy.persistence.domain.LeadTimeline[\"timelineContent\"])","exceptionTime":"2019-06-19 08:59:12"}

没找指定类型为String不做转换的方法

暂时解决办法

Json.put("timelineContent",timelineContent==null?null:" "+timelineContent);

然后接口方就能正确识别了。。。

以上是“JSONObject如何实现按put顺序排放与输出”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注天达云行业资讯频道!

返回开发技术教程...