使用Gson將Java對象轉(zhuǎn)換為JSON文章分類:Java編程 關(guān)鍵字: gson json javaGson是Google的一個(gè)開源項(xiàng)目,,可以將Java對象轉(zhuǎn)換成JSON,,也可能將JSON轉(zhuǎn)換成Java對象,。
Gson里最重要的對象有2個(gè)Gson 和 GsonBuilder
Gson有2個(gè)最基本的方法
下面是幾個(gè)小例子 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); 會(huì)輸出 {"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對象的屬性轉(zhuǎn)換成指定的JSON名字
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); 輸出結(jié)果 {"first_field":"aaaa","SecondField":"bbbbb"}
原文 - http://www./java/how-do-convert-java-object-to-from-json-format-gson-api/ Json Official site – http://www./ Json in Wiki – http://en./wiki/JSON Google Gson – http://code.google.com/p/google-gson/ Gson User Guide - http://sites.google.com/site/gson/gson-user-guide (訪問須翻墻, 請自備梯子) |
|