gson(json转对象和对象转json的方法)

Gson是Google的一个开源项目,可以将Java对象转换成JSON,也可能将JSON转换成Java对象。

 

Gson里最重要的对象有2个Gson 和 GsonBuilder

 

Gson有2个最基本的方法
1) toJson() – 转换java 对象到JSON
2) fromJson() – 转换JSON到java对象

 

下面是几个小例子

1. toJson() example

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

 

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名字

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);

 输出结果 {"first_field":"aaaa","SecondField":"bbbbb"}

你可能感兴趣的:(java,json,String,Google,Class,import)