JSONObject按put順序排放與輸出方式
JSONObject按put順序排放與輸出
JSONObject put數據之后,排序會發(fā)生變化
例如
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);
然后接口方就能正確識別了。。。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springboot2.0?@Slf4j?log?彩色日志配置輸出到文件
這篇文章主要介紹了springboot2.0 @Slf4j log日志配置輸出到文件(彩色日志),解決方式是使用了springboot原生自帶的一個log框架,結合實例代碼給大家講解的非常詳細,需要的朋友可以參考下2023-08-08Spring Cloud Gateway + Nacos 實現動態(tài)路由
這篇文章主要介紹了Spring Cloud Gateway + Nacos 實現動態(tài)路由的方法,幫助大家實現路由信息的自動更新,感興趣的朋友可以了解下2020-10-10