1.gson
官网https://github.com/google/gson
1.1 maven
1 2 3 4 5 6 7 8 9
| <dependencies> <!-- Gson: Java to Json conversion --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> <scope>compile</scope> </dependency> </dependencies>
|
2.基本方法
- gson.toJson 将对象转换成json字符串
- gson.fromJson 将json字符串转换为object对象
2.1 toJson方法
定义一个对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Res1 { private String jsonrpc; private String result; private Integer id; public String getResult() { return result; } public void setId(Integer id) { this.id = id; } public void setJsonrpc(String jsonrpc) { this.jsonrpc = jsonrpc; } public void setResult(String result) { this.result = result; } }
|
可以不用定义setter函数,用构造函数赋值,然后:
1 2 3 4 5
| Res1 r1 = new Res1(); Res1.setId() ... Gson gson = new Gson(); Res1 r1 = gson.toJson();
|
就可以转成json字符串。
2.2 fromJson方法
1 2 3
| String j1 = JSON_STRING Gson gson = new Gson(); Res1 res1 = gson.fromJson(JSON_STRING, Res1.class)
|