json-lib的字符串自动转换坑
生活随笔
收集整理的這篇文章主要介紹了
json-lib的字符串自动转换坑
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、場景復現
(1)代碼
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import net.sf.json.JSONObject;public class C {public static void main(String[] args){JSONObject json = new JSONObject();json.put("str0","hello");json.put("str1","\"hello\"");json.put("str2"," \"hello \" ");json.put("str3","\"hello \"\n");json.put("jsonObj0","{\"count\":\"23\"}");json.put("jsonObj1","{\"count\":\"23\"}\n");json.put("jsonObj2"," {\"count\":\"23\"} ");json.put("jsonObj3","{\"count\":\"23\",size:2}");json.put("jsonObj4","{\"count\":\"23\",size:}");json.put("jsonArr0","[1,2]");json.put("jsonArr1"," [1,2]");json.put("jsonArr2","[1,2]\n");json.put("jsonArr3","\"[1,2]\"");json.put("jsonArr4","[1,2,-]");json.put("jsonArr5","[1,2,A]");System.out.println(format(json.toString()));}public static String format(String json) {JsonParser jsonParser = new JsonParser();JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();Gson gson = new GsonBuilder().setPrettyPrinting().create();return gson.toJson(jsonObject);}} <dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version></dependency>(2)輸出
json-lib-2.3輸出:
<dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.3</version><classifier>jdk15</classifier> </dependency> {"str0": "hello","str1": "hello","str2": " \"hello \" ","str3": "\"hello \"\n","jsonObj0": {"count": "23"},"jsonObj1": "{\"count\":\"23\"}\n","jsonObj2": " {\"count\":\"23\"} ","jsonObj3": {"count": "23","size": 2},"jsonObj4": "{\"count\":\"23\",size:}","jsonArr0": [1,2],"jsonArr1": " [1,2]","jsonArr2": "[1,2]\n","jsonArr3": "[1,2]","jsonArr4": [1,2,"-"],"jsonArr5": "[1,2,A]" }json-lib-2.4輸出:
<dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier> </dependency> {"str0": "hello","str1": "\"hello\"","str2": " \"hello \" ","str3": "\"hello \"\n","jsonObj0": {"count": "23"},"jsonObj1": "{\"count\":\"23\"}\n","jsonObj2": " {\"count\":\"23\"} ","jsonObj3": {"count": "23","as": 2},"jsonObj4": "{\"count\":\"23\",as:}","jsonArr0": [1,2],"jsonArr1": " [1,2]","jsonArr2": "[1,2]\n","jsonArr3": "[1,2]","jsonArr4": [1,2,"-"],"jsonArr5": "[1,2,A]" }(3)異常現象
字符串"\"xx\""轉換成"xx","{\"key\":value}"轉成{"key":value}對象,"[value,vlaue]""轉成[value,vlaue]對象
json-lib版本不同:json-lib-1.3把"\"xx\""轉換成"xx","{\"key\":value}"轉成{"key":value}對象,"[value,vlaue]""轉成[value,vlaue]對象
json-lib-1.4的"\"xx\""不轉換,而"{\"key\":value}"轉成{"key":value}對象,"[value,vlaue]""轉成[value,vlaue]對象
?
二、原因
json-lib與Gson等其他JSON庫不一樣,會默認將json字符串(包含雙引號字符串)轉換json對象。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的json-lib的字符串自动转换坑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Executor 与 ExecutorS
- 下一篇: IDEA的debug方法头坑