使用Gson将Java对象转换为JSON
Gson是Google的一个开源项目,可以将Java对象转换成JSON,也可能将JSON转换成Java对象。
Gson里最重要的对象有2个Gson 和 GsonBuilder
Gson有2个最基本的方法
1) toJson() – 转换java 对象到JSON
2) fromJson() – 转换JSON到java对象
下面是几个小例子
1. toJson() example
Java代码
- 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代码
- 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代码
- 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"}
原文 - http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/