Gson是Google的一个开源项目,可以将Java对象转换成JSON,也可能将JSON转换成Java对象。
Gson里最重要的对象有2个Gson 和 GsonBuilder
Gson有2个最基本的方法
1) toJson() – 转换java 对象到JSON
2) fromJson() – 转换JSON到java对象
下面是几个小例子
1. toJson() example
Java 代码 收藏代码
1. class TestObjectToJson {
2. private int data1 = 100;
3. private String data2 = "hello";
4. }
5.
6. TestObjectToJson obj = new TestObjectToJson();
7. Gson gson = new Gson();
8. String json = gson.toJson(obj);
class TestObjectToJson {
private int data1 = 100;
private String data2 = "hello";
}
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
String json = gson.toJson(obj);
会输出 {"data1":100,"data2":"hello"}
2. fromJson() example
Java 代码 收藏代码
1. import com.google.gson.Gson;
2.
3. class TestJsonFromObject {
4. private int data1;
5. private String data2;
6. }
7.
8. String json = "{'data1':100,'data2':'hello'}";
9. Gson gson = new Gson();
10. TestJsonFromObject obj = gson.fromJson(json, TestJsonFromObject.class);
import com.google.gson.Gson;
class TestJsonFromObject {
private int data1;
private String data2;
}
String json = "{'data1':100,'data2':'hello'}";
Gson gson = new Gson();
TestJsonFromObject obj = gson.fromJson(json, TestJsonFromObject.class);
3. 将Java对象的属性转换成指定的JSON名字
Java 代码 收藏代码
1. import com.google.gson.FieldNamingPolicy;
2. import com.google.gson.Gson;
3. import com.google.gson.GsonBuilder;
4. import com.google.gson.annotations.SerializedName;
5.
6. public class TestGson {
7.
8. @SerializedName("first_field")
9. private String field1;
10.
11. private String secondField;
12.
13. public TestGson(String param1, String param2) {
14. field1 = param1;
15. secondField = param2;
16. }
17. }
18.
19. TestGson obj = new TestGson("aaaa", "bbbbb");
20. Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
21. gson.toJson(obj);
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class TestGson {
@SerializedName("first_field")
private String field1;
private String secondField;
public TestGson(String param1, String param2) {
field1 = param1;
secondField = param2;
}
}
TestGson obj = new TestGson("aaaa", "bbbbb");
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
gson.toJson(obj);
输出结果 {"first_field":"aaaa","SecondField":"bbbbb"}