Gson--Gson解析=等號出現亂碼?


 

GSON使用筆記(1) -- 序列化時排除字段的幾種方式

 

 

 

--3,關於Gson解析時候特殊符號,被轉義的問題,如’單引號?


//Creating the JSON object, and getting as String:
JsonObject json = new JsonObject();
JsonObject inner = new JsonObject();
inner.addProperty("value", "xpath('hello')");
json.add("root", inner);
System.out.println(json.toString());

//Trying to pretify JSON String:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(json.toString());
System.out.println(gson.toJson(je));
輸出

{"root":{"value":"xpath('hello')"}}

{
"root": {
"value": "xpath(\u0027hello\u0027)"
}
}

解決辦法:
Gson gs = new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create();

 

---2, Gson將一些字符自動轉換為Unicode轉義字符,怎么辦?

最近用富文本編輯器,編輯微信素材的時候,發現微信群發的消息內容中有許多Unicode編碼字符。
后來發現是Gson使用不當的問題。
Gson gson = new Gson();
String articleListStr = gson.toJson(articleList); //將素材上傳到微信服務器,系統群發的消息,其實是微信服務器上的素材。
String resposeString = HttpUtils.post(createNewsUrl,articleListStr);

原來,Gson會把html標簽,轉換為Unicode轉義字符。導致微信群發內容異常。

正確的使用方法是:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();

 

--1, GSON解析=等號出現亂碼?

最近項目中使用gson來將對象轉換為json字符串的時候,竟然出現了亂碼的問題!

使用如下代碼:
new Gson().toJson(http://www.baidu.com/id=1);

結果卻是:“http://www.baidu.com/id\u003d1 ”

后來看了一下GsonBuilder才找到解決問題的方法
GsonBuilder gb =new GsonBuilder();
gb.disableHtmlEscaping();
gb.create().toJson("http://www.baidu.com/id=1");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM