Android Open Source Library--gson Google official JSON parsing library

Source: Internet
Author: User
Tags tojson

Official Document Address: http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

Official website: http://code.google.com/p/google-gson/

JSON official website: http://www.json.org/json-zh.html

At present, the mainstream data transmission is using JSON, parsing JSON and converting to the corresponding type is the only way.

Native Andoird is self-parsing JSON, but it is not easy to use before using Gson.

First introduce the Android native parsing

Contains four JSON-related classes and a exceptions in Android:
Jsonarray
Jsonobject
Jsonstringer
Jsontokener
Jsonexception

(1) Jsonobject:
This is the basic unit in the system for JSON definition, which contains a pair of key/value values.
Its response to the external (External: Apply the ToString () method output value) is reflected as a standard string (for example: {"JSON": "Hello, World"}, enclosing the outer brace with the key and value separated by the colon ":"). Its action format for internal (Internal) behavior is slightly, for example: Initializing a Jsonobject instance, referencing the internal put () method to add a value: New Jsonobject (). Put ("JSON", "Hello, world!"), Between key and value is separated by a comma ",".
The types of value include: Boolean, Jsonarray, Jsonobject, number, string, or the default value Jsonobject.null object.
There are two different methods of fetching values:
Get (): used when determining the existence of a value, or a exception message will be thrown when the relevant key cannot be retrieved.
Opt (): This method is relatively flexible and returns a default value when the specified value cannot be obtained, and does not throw an exception.

(2) Jsonarray:
It represents an ordered set of values. Converting it to a string output (toString) is performed in the form of a square bracket, separated by a comma "," (for example: [Value1,value2,value3], you can personally use the short code to understand its format more intuitively). The inside of this class also has query behavior, both get () and opt () can return the specified value through the index index, and the put () method is used to add or replace values.
Similarly, the value type of this class can include: Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.

That's how it's used.

//turn this JSON data into an object. Jsonobject Jsonobject =NewJsonobject (String);//and get the data from the list.Jsonarray Jsonarray = Jsonobject.getjsonarray ("List");//When you do not know the key, use the loop for(intI=0; I<jsonarray.length (); i++) {Jsonobject jsonob=(jsonobject) jsonarray.opt (i); intTel = jsonob.getint ("Tel"); }

(3) Jsonstringer:
According to the official explanation, this class can help create jsontext quickly and easily. Its greatest advantage is that it can reduce program exceptions due to format errors, which can automatically create JSON text in strict accordance with JSON syntax rules (syntaxrules). Each Jsonstringer entity can only create one JSON text.

New Jsonstringer (). Object (). Key ("name"). Value (" piglet "). EndObject (). toString ();   // The result is a set of standard format JSON text:{"name": "Piglet"}

The. Object () and. EndObject () must be used together in order to add a boundary to the value according to the object standard. Similarly, there is a standard set of methods for arrays to generate boundaries. Array () and. Endarray ().

(4) Jsontokener:
This is the class for the system to parse the JSON source string for the Jsonobject and Jsonarray constructors, which can extract numeric information from the source string.
(5) Jsonexception:
Is the exception information thrown by the Json.org class.

Since the use of Gson, everything has become simple.

Gson has two important methods, one is ToJson, the other is Fromjson, which is serialization and deserialization.

Very simple to use.

Gson Gson =NewGson ();//Serialization ofMyObject myobj =NewMyObject (); String Jsonstr=Gson. ToJson (myobj);//deserializationMyObject myobj = Gson.fromjson (Jsonstr, MyObject.class); //Serializing ArraysString[] days = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; String Numbersjson=Gson.tojson (numbers);//Serializing a collectionList<string> MYOBJS =NewArraylist<string>(); String Jsonstr=Gson.tojson (MYOBJS);//deserialize an array of collectionslist<myobject> MYOBJS = Gson.fromjson (str,NewTypetoken<arraylist<myobject>> () {}.gettype ());

At the same time Gson also supports the use of annotations, in the Com.google.gson.annotation package, there are several annotations expose, serializedname, since and until, they each have their own role, the following use the official example to introduce common annotations:

Expose

This annotation acts on the property, indicating that when serialized and deserialized, this property will be exposed to the Gson object. This annotation is valid only if the Gsonbuilder.excludefieldswithoutexposeannotation () method is created and called using Gsonbuilder mode when the Gson object is created, otherwise it is not valid. Here is an example of how @expose annotations are used:

 public  class   User {@Expose  private   String FirstName; @Expose (Serialize  = false ) private   String LastName; @Expose (Serialize  =  False , deserialize = false ) private   String EmailAddress;  private   String password;}  

If you create a Gson object in the form of New Gson (), the ToJson () method and the Fromjson () method will manipulate these 4 properties when serializing and deserializing. However, if you use Gson Gson = new Gsonbuilder (). Excludefieldswithoutexposeannotation (). Create () creates Gson objects, Gson ToJson () and The Fromjson () method will exclude the password field because the password field is not marked by the annotation @Expose. This Gson object also excludes the LastName and EmailAddress fields, because the annotation @expose property serialize is set to false. Similarly, Gson will remove the EmailAddress field when deserializing, because deserialize is set to false.

Ps:

If you do not want to have some properties, you can also use transient masking, such as:

transient int val;

Serializedname

This annotation acts on a property, indicating that this property, when serialized as JSON, needs to serialize the name to the value specified by the annotation's Value property.

This annotation will overwrite any fieldnamingpolicy, including the default naming policy. Here is an example of how @serializedname annotations are used:

 Public class Someclasswithfields {   @SerializedName (privatefinal  String Somefield;     Private Final String Someotherfield;      Public Someclasswithfields (String A, string b) {      this. Somefield = A;        this. Someotherfield = b;   }}

The serialization result is: {"name": "A", "Someotherfield": "B"}

Since

Use the @since annotation to maintain the version, such as you have a rest API, and there are multiple versions of JSON, if the next version of the JSON added fields, but do not want all the versions are used in these fields, you can use

 Public classExample33 { Public Static voidMain (string[] args) {Gson Gson=NewGsonbuilder (). Setversion (2.0). Create (); String JSON= Gson.tojson (NewExampleClass ()); System.out.println ("Output for version 2.0 ...");            SYSTEM.OUT.PRINTLN (JSON); Gson=NewGsonbuilder (). Setversion (1.0). Create (); JSON= Gson.tojson (NewExampleClass ()); System.out.println ("\noutput for version 1.0 ...");            SYSTEM.OUT.PRINTLN (JSON); Gson=NewGson (); JSON= Gson.tojson (NewExampleClass ()); System.out.println ("\noutput for No version set ...");    SYSTEM.OUT.PRINTLN (JSON); }  }     classexampleclass{String Field= "Field"; //This was in version 1.0@Since (1.0) String newField1 = "Field 1"; //Following'll be included in the version 1.1@Since (2.0) String newField2 = "Field 2"; }  

The output is:
Output for version 2.0 ...
{"Field": "Field", "NewField1": "Field 1", "NewField2": "Field 2"}

Output for version 1.0 ...
{"Field": "Field", "NewField1": "Field 1"}

Output for No version set ...
{"Field": "Field", "NewField1": "Field 1", "NewField2": "Field 2"}

Until

As opposed to since, if a field is deleted in the next version of JSON, it can be used, as in the same principle.

After using annotations, we need to create Gson

Gsonbuilder

Set the parameters as follows

Gson Gson =NewGsonbuilder (). Excludefieldswithoutexposeannotation ()//do not export attributes with @expose annotations in the entity. Enablecomplexmapkeyserialization ()//Map-enabled key is the form of a complex object. Serializenulls (). Setdateformat ("Yyyy-mm-dd HH:mm:ss:SSS")//time into a specific format. Setfieldnamingpolicy (Fieldnamingpolicy.upper_camel_case)//The first letter of the field is capitalized, note: The @serializedname annotation used on the entity will not take effect. . Setprettyprinting ()//formats the JSON result. . Setversion (1.0). disablehtmlescaping ()//The default is Gson to escape HTML, but can also be set to not escape. Serializenulls ()//The null value is also converted, the default is not to convert null values, you can choose to also convert. Create ();

Reference website:

http://jiuyuehe.iteye.com/blog/1882800

http://shazhuzhu1.iteye.com/blog/974758

http://jackyrong.iteye.com/blog/2004374

http://blog.csdn.net/lk_blog/article/details/7685190

Android Open Source Library--gson Google official JSON parsing library

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.