Android Json processing-Gson
Overview: java json Parsing Library. (Others are similar to json-lib, Jackson, fastson) Core class: Gson or GsonBuilder uses jsonschema2pojo to create POJO1. Create POJO1 online through website: select the source code type as Json and the annotation type as Gson, click preview. 2. Run the command line tool jsonschema2pojo. bat-a GSON-t json -- source jsonaddress -- target java-gen
You can use new Gson () or GsonBuilder to build Gson objects.
(Serialization)Gson gson = new Gson();gson.toJson(1); ==> prints 1gson.toJson(abcd); ==> prints abcdgson.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 objNested Classes (including Inner Classes) Gson can easily serialize static and static internal Classes (but not 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
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
>(){}.getType();Collection
ints2 = gson.fromJson(json, collectionType);
Serializing and Deserializing Generic Types
Type fooType = new TypeToken
>() {}.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 by default, Gson's json Output has no space and is worth ignoring null, so it is not very friendly. We can use pretty output and output null at the same time.
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 this article does not introduce Excluding Fields From Serialization and Deserialization. By default, transient and static field are ignored. However, if you want to include some transient fields, you can take the following form:
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();
But there are better forms to take
@ Expose Annotation: Then call new GsonBuilder (). excludeFieldsWithoutExposeAnnotation (). create () to create Gson fan
Fields annotated by @ Expose are included, and those not annotated are ignored.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 functions New Methods in JsonArray
@ TypeAdapter Annotation
JsonPath Support