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);
然后接口方就能正确识别了。。。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
解决BeanUtils.copyProperties无法成功封装的问题
这篇文章主要介绍了解决BeanUtils.copyProperties无法成功封装的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06
Idea springboot springCloud热加载热调试两种常用方式
这篇文章主要介绍了Idea springboot springCloud热加载热调试常用的两种方式,在项目开发的过程中,需要修改调试的时候偶每次都需要重启项目浪费时间,下面是我整理的两种常用的两种方式,需要的朋友可以参考下2023-04-04
SpringBoot实现application.yml文件敏感信息加密
本文主要介绍了SpringBoot实现application.yml文件敏感信息加密,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-07-07


最新评论