Android Json處理之Gson

來源:互聯網
上載者:User

標籤:json

概述:項目地址:https://github.com/google/gsonGson:java的json解析庫。(其他類似的有json-lib,Jackson,fastson)核心類:Gson或者GsonBuilder使用jsonschema2pojo來建立POJO1、通過網站http://www.jsonschema2pojo.org/線上建立:選擇原始碼類型為Json,註解類型是Gson,然後點擊preview.2、通過命令列工具:jsonschema2pojo.bat -a GSON -T JSON --source jsonaddress --target java-gen
使用Gson你可以使用new Gson()或者通過GsonBuilder來構建Gson對象。
(Serialization)Gson gson = new Gson();gson.toJson(1);            ==> prints 1gson.toJson("abcd");       ==> prints "abcd"gson.toJson(new Long(10)); ==> prints 10int[] values = { 1 };gson.toJson(values);       ==> prints [1](Deserialization)int one = gson.fromJson("1", int.class);Integer one = gson.fromJson("1", Integer.class);Long one = gson.fromJson("1", Long.class);Boolean false = gson.fromJson("false", Boolean.class);String str = gson.fromJson("\"abc\"", String.class);String anotherStr = gson.fromJson("[\"abc\"]", String.class);
class BagOfPrimitives {  private int value1 = 1;  private String value2 = "abc";  private transient int value3 = 3;  BagOfPrimitives() {    // no-args constructor  }}(Serialization)BagOfPrimitives obj = new BagOfPrimitives();Gson gson = new Gson();String json = gson.toJson(obj);  ==> json is {"value1":1,"value2":"abc"}Note that you can not serialize objects with circular references since that will result in infinite recursion. (Deserialization)BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);   ==> obj2 is just like obj
Nested Classes (including Inner Classes)Gson可以很容易地序列化靜態static的內部類(但是非靜態這不能)Array Examples
Gson gson = new Gson();int[] ints = {1, 2, 3, 4, 5};String[] strings = {"abc", "def", "ghi"};(Serialization)gson.toJson(ints);     ==> prints [1,2,3,4,5]gson.toJson(strings);  ==> prints ["abc", "def", "ghi"](Deserialization)int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
Collections Examples
Gson gson = new Gson();Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);(Serialization)String json = gson.toJson(ints); ==> json is [1,2,3,4,5](Deserialization)Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();Collection<Integer> ints2 = gson.fromJson(json, collectionType);
Serializing and Deserializing Generic Types
Type fooType = new TypeToken<Foo<Bar>>() {}.getType();gson.toJson(foo, fooType);gson.fromJson(json, fooType);
Serializing and Deserializing Collection with Objects of Arbitrary TypesSometimes you are dealing with JSON array that contains mixed types. For example: [‘hello‘,5,{name:‘GREETINGS‘,source:‘guest‘}]
public class RawCollectionsExample {  static class Event {    private String name;    private String source;    private Event(String name, String source) {      this.name = name;      this.source = source;    }    @Override    public String toString() {      return String.format("(name=%s, source=%s)", name, source);    }  }  @SuppressWarnings({ "unchecked", "rawtypes" })  public static void main(String[] args) {    Gson gson = new Gson();    Collection collection = new ArrayList();    collection.add("hello");    collection.add(5);    collection.add(new Event("GREETINGS", "guest"));    String json = gson.toJson(collection);    System.out.println("Using Gson.toJson() on a raw collection: " + json);    JsonParser parser = new JsonParser();    JsonArray array = parser.parse(json).getAsJsonArray();    String message = gson.fromJson(array.get(0), String.class);    int number = gson.fromJson(array.get(1), int.class);    Event event = gson.fromJson(array.get(2), Event.class);    System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event);  }}
Compact Vs. Pretty Printing for JSON Output Format預設情況下Gson的json輸出是沒有空格與忽略null值得,所以不是很友好。我們可以採用pretty輸出,同時輸出null
Gson gson = new GsonBuilder().setPrettyPrinting().serialzeNulls().create();
NOTE: when serializing nulls with Gson, it will add a JsonNull element to the JsonElement structure. Therefore, this object can be used in custom serialization/deserialization.Versioning Support本文不做介紹Excluding Fields From Serialization and Deserialization預設情況下transient 和static field是被忽略的。但是如果你想包含某些transient域可以採取如下形式:
import java.lang.reflect.Modifier;Gson gson = new GsonBuilder()    .excludeFieldsWithModifiers(Modifier.STATIC)    .create();NOTE: you can use any number of the Modifier constants to "excludeFieldsWithModifiers" method.  For example:Gson gson = new GsonBuilder()    .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)    .create();
不過有更好的形式可以採取 @Expose註解:然後調用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()建立Gson凡 是被@Expose註解的域都會被包括,沒有被註解的都被忽略。JSON Field Naming Support  @SerializedName
private class SomeObject {  @SerializedName("custom_naming") private final String someField;  private final String someOtherField;  public SomeObject(String a, String b) {    this.someField = a;    this.someOtherField = b;  }}SomeObject someObject = new SomeObject("first", "second");Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();String jsonRepresentation = gson.toJson(someObject);System.out.println(jsonRepresentation);======== OUTPUT ========{"custom_naming":"first","SomeOtherField":"second"}
Gson2.3新的功能New Methods in JsonArray
@TypeAdapter Annotation
JsonPath Support

參考:https://sites.google.com/site/gson/gson-user-guide
http://www.studytrails.com/java/json/java-google-json-new-2.3.jsp








Android Json處理之Gson

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.