Overview: Project Address: JSON parsing library for Https://github.com/google/gsonGson:java. (Other similar Json-lib,jackson,fastson) Core classes: Gson or Gsonbuilder use Jsonschema2pojo to create POJO1 and create them online via the site http://www.jsonschema2pojo.org/:Select the source code type is JSON, the annotation type is Gson, and then click Preview.2. Via command line tool: Jsonschema2pojo.bat-a gson-t JSON--source jsonaddress--target Java-gen
With Gson you can use new Gson () or Gsonbuilder to build Gson objects.
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 so can not serialize objects with circular references since that would result in infinite recursion. (deserialization) Bagofprimitives obj2 = Gson.fromjson (JSON, bagofprimitives.class); ==> obj2 is just like obj
Nested Classes (including Inner Classes) Gson can easily serialize internal classes of static statics (but non-static this cannot) 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);
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 is dealing with JSON array that con Tains 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 the JSON outputs of Gson are no spaces and ignoring null is worthwhile, so not very friendly. We can use the pretty output and output null at the same time
Gson Gson = new Gsonbuilder (). setprettyprinting (). Serialzenulls (). Create ();
Note:when serializing nulls with Gson, it'll add a jsonnull element to the jsonelement structure. Therefore, this object can is used in custom serialization/deserialization. Versioning support This article does not introduce excluding field from serialization and deserialization by default transient and static fields are ignored. But if you want to include some transient domains 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 that can be taken
@Expose Annotations: Then call new Gsonbuilder (). Excludefieldswithoutexposeannotation (). Create () creates Gson
fields that are annotated by @expose are included and ignored without annotations. 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
Reference:Https://sites.google.com/site/gson/gson-user-guide
http://www.studytrails.com/java/json/java-google-json-new-2.3.jsp
Gson of Android JSON processing