Google-Gson

Gson笔记

google / gson https://github.com/google/gson

Gson将=序列化为\u003d

Base64中会用 = 填充,如果使用默认 Gson 做序列化,= 会被转化化为 \u003d

解决方案: disableHtmlEscaping https://www.javadoc.io/static/com.google.code.gson/gson/2.8.6/com.google.gson/com/google/gson/GsonBuilder.html#disableHtmlEscaping()

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String s2 = gson.toJson(hm.toString());

GSON issue with String https://stackoverflow.com/questions/16558709/gson-issue-with-string

实体转换为Json

import com.google.gson.Gson;

RetEntity re = new RetEntity();
... ...
Gson g = new Gson();
String json = g.toJson(re);

Json转换为实体

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

Gson g = new Gson();
try{
    ReqEntity re = g.fromJson(json, ReqEntity.class);
}catch(JsonSyntaxException jse){
    logger.error(jse.getMessage())
}

null值

gson默认是不序列化null值对应的key的,若是想序列化null值对应的key,需要使用com.google.gson.GsonBuilder类创建Gson对象:

Gson g = new GsonBuilder().serializeNulls().create();

参考: Json转换神器之Google Gson的使用 http://my.oschina.net/itblog/blog/204120

5分钟 玩转google Gson http://jiuyuehe.iteye.com/blog/1882800

介绍4款json的java类库 及 其性能测试 http://www.cnblogs.com/windlaughing/p/3241776.html

FastJson、Jackson、Gson进行Java对象转换Json的细节处理 http://blog.csdn.net/moneyshi/article/details/51830329