Gson Fromjson () usage

Source: Internet
Author: User
Tags tagname tojson

1. Pure array JSON

String conversions

[{"Name": "Zhangsan", "Age": "Ten", "Phone": "11111", "email": "[email protected]"},

{"Name": "Lisi", "Age": "a", "Phone": "22222", "email": "[email protected]"},

  ... ]

The parsing code is as follows:

public class UserBean {

//variable names must match JSON data field names

private String name;

Private String age;

Private String phone;

Private String Email;

...

}

Get the local JSON and turn it into a string

String Strbyjson = Constructtestjsonstr ();//omission of function contents here

Parsing class objects for JSON

Jsonparser parser = new Jsonparser ();

Converts a string of JSON into a Jsonarray object

Jsonarray Jsonarray = Parser.parse (Strbyjson). Getasjsonarray ();

Gson Gson = new Gson ();

arraylist<userbean> userbeanlist = new arraylist<> ();

Enhanced for Loop traversal Jsonarray

for (Jsonelement User:jsonarray) {

Use Gson to turn directly into bean objects

UserBean UserBean = Gson.fromjson (user, userbean.class);

Userbeanlist.add (UserBean);

}

2. A pure array with data headers

Data conversion

{"Muser": [{"Name": "Zhangsan", "Age": "Ten", "Phone": "11111", "email": "[email protected]"},
           {"Name": "Lisi", "Age": "a", "Phone": "22222", "email": "[email protected]"},

...]
}

Parsing a pure array with a data header

Get the local JSON and turn it into a string

String Strbyjson = Constructtestjsonstr ();//The contents of this function are omitted;

Turn Jsonobject first.

Jsonobject jsonobject = new Jsonparser (). Parse (Strbyjson). Getasjsonobject ();

Re-Jsonarray plus data header

Jsonarray Jsonarray = Jsonobject.getasjsonarray ("Muser");

Gson Gson = new Gson ();

arraylist<userbean> userbeanlist = new arraylist<> ();

Looping through

for (Jsonelement User:jsonarray) {

Get Userbean.class by Reflection

UserBean UserBean = Gson.fromjson (user, new typetoken<userbean> () {}.gettype ());

Userbeanlist.add (UserBean);

}

3. There is a complex data header

Data conversion

"Code": $, "msg": "OK",
"Muser": [{"Name": "Zhangsan", "Age": "Ten", "Phone": "11111", "email": "[email protected]"},
      {"name": "Lisi", "Age": "a", "Phone": "22222", "email": "[email protected]"},
        ...]
}

The parsed object is not a pure array of data, there are other fields + arrays (with headers), as follows:

Build the bean based on JSON, note that the bean here is returning all fields, because Gson can parse directly into List, so the bean is the following, and also the get/set that occupy the place is omitted:

public class Resultbean {
//Note the variable name must be the same as the field name
private int code;
Private String msg;
Private list<userbean> Muser;
public class userbean{
private String name;
Private String age;
Private String phone;
Private String Email;
...
}
...
}
There is a general method of message head complex data as follows
Get the JSON string
String Strbyjson = Constructtestjsonstr ();//The contents of this function are omitted;
Gson Direct parse into object
Resultbean Resultbean = new Gson (). Fromjson (Strbyjson,resultbean.class);
Get the collection in the object
list<resultbean.userbean> userbeanlist = Resultbean.getmuser ();
Three sentences to take care of, thus see Gson Strong

4. Parse only the complex JSON

A portion of an array or array of contents

Data head Complex data interception method, such as the 3rd example of the JSON data content only want to take "Muser" array of age is more than 30 years old how to do?

Method 1: Parse all, and then take from list. (But what if there were 10,000 data?) All parsing is too troublesome), Method 2: Conditional traversal! (The following code example):

Parsing code:

Get the JSON string

String Strbyjson = Constructtestjsonstr ();//The contents of this function are omitted;

list<userbean> userbeanlist = new arraylist<> ();

Get the array

Jsonobject jsonobject = new Jsonparser (). Parse (Strbyjson). Getasjsonobject ();

Jsonarray Jsonarray = Jsonobject.getasjsonarray ("Muser");

Iterating through an array

for (Jsonelement User:jsonarray) {

UserBean UserBean = new Gson (). Fromjson (User, new typetoken<userbean> () {

}.gettype ());

Filter by condition

if (Integer.parseint (Userbean.getage ()) > 30) {

Userbeanlist.add (UserBean);

}

}

5. Nesting Ultra-complex JSON

Data conversion

Three ways: 1, all parse out; 2, what to parse what; 3,jsonreader, 1th/2 strokes explained above, the following example Jsonreader (similar to the node-wise interpretation of XML)

Through the Jsonreader way to parse

private void Parsecomplexjarraybyreader () throws IOException {

String Strbyjson = Jsontostringutil.getstringbyjson (this, r.raw.juser_4);

Jsonreader reader = new Jsonreader (new StringReader (Strbyjson));

try {

Reader.beginobject ();

String tagName = Reader.nextname ();

if (Tagname.equals ("group")) {

Read Group this node

Readgroup (reader);

}

Reader.endobject ();

} finally {

Reader.close ();

}

}

Read Group this node

private void Readgroup (Jsonreader reader) throws IOException {

Reader.beginobject ();

while (Reader.hasnext ()) {

String tagName = Reader.nextname ();

if (tagname.equals ("user")) {

Readuser (reader);

} else if (tagname.equals ("info")) {

Readinfo (reader);

}

}

Reader.endobject ();

}

Read the user basic message the Users node

private void Readuser (Jsonreader reader) throws IOException {

Reader.beginobject ();

while (Reader.hasnext ()) {

String tag = Reader.nextname ();

if (tag.equals ("name")) {

String name = Reader.nextstring ();

Nametext.settext (name);

} else if (Tag.equals ("Age")) {

String age = reader.nextstring ();

Agetext.settext (age);

}

...

else {

Reader.skipvalue ();//Ignore

}

}

Reader.endobject ();

}

Read user other Messages Info node

private void Readinfo (Jsonreader reader) throws IOException {

Reader.beginobject ();

while (Reader.hasnext ()) {

String tag = Reader.nextname ();

if (Tag.equals ("address")) {

String address = reader.nextstring ();

Addresstext.settext (address);

} else if (Tag.equals ("work")) {

String work = reader.nextstring ();

Worktext.settext (work);

}

...

else {

Reader.skipvalue ();//Ignore

}

}

Reader.endobject ();

}

6. Simple Data +list+map

Transformation

public class Student {

public int id;

Public String nickname;

public int age;

public arraylist<string> Books;

Public hashmap<string, string> Booksmap;

}

Student Student = new Student ();

Student.id = 1;

Student.nickname = "Jack";

Student.age = 22;

Student.email = "[email protected]";

arraylist<string> books = new Arraylist<string> ();

Books.add ("mathematics");

Books.add ("language");

Books.add ("English");

Books.add ("physical");

Books.add ("chemistry");

Books.add ("biology");

Student.books = books;

hashmap<string, string> booksmap = new hashmap<string, string> ();

Booksmap.put ("1", "mathematics");

Booksmap.put ("2", "language");

Booksmap.put ("3", "English");

Booksmap.put ("4", "Physical");

Booksmap.put ("5", "chemistry");

Booksmap.put ("6", "creature");

Student.booksmap = Booksmap;

Gson Gson = new Gson ();

String result = Gson.tojson (student);

Student STUDENTG = Gson.fromjson (result, student.class);

LOG.E ("Mainactivity", "ID:" + studentg.id);

LOG.E ("Mainactivity", "nickname:" + Studentg.nickname);

LOG.E ("Mainactivity", "Age:" + studentg.age);

LOG.E ("mainactivity", "Email:" + studentg.email);

LOG.E ("Mainactivity", "Books Size:" + studentG.books.size ());

LOG.E ("Mainactivity", "Booksmap Size:" + studentG.booksMap.size ());

Print output

Id:1

Nickname:jack

Age:22

Email:[email protected]

Books Size:6

Booksmap Size:6

7. list or map etc. Collection

The generics are replaced with a custom class

Generic definition

Public hashmap<string,book> Booksmap;

public class book{

public int id;

public String name;

}

hashmap<string, book> booksmap = Gson.fromjson (result, new typetoken

Gson Gson = new Gson ();

hashmap<string, book> booksmap = new hashmap<> ();

Booksmap.put ("Book1", new book (1, "Java Foundation Development"));

Booksmap.put ("Book2", New book (2, "Java design mode"));

Booksmap.put ("Book3", New book (3, "Java Algorithm"));

String datastr = Gson.tojson (Booksmap);

System.out.println ("Datastr:" + datastr);

hashmap<string, book> booksMap2 = Gson.fromjson (datastr, New typetoken

}.gettype ());

For (map.entry<string, book> entry:booksMap2.entrySet ()) {

System.out.println ("Key:" +entry.getkey () + "value:" + entry.getvalue (). toString ());

}

Output results

datastr:{"Book2": {"id": 2, "name": "Java design mode"}, "Book1": {"id": 1, "name": "Java Basic Development"}, "Book3": {"id": 3, "name": "Java Algorithm" }}

Key:book2 value:book{id=2, name= ' Java design mode '}

Key:book1 value:book{id=1, Name= ' Java Foundation development '}

Key:book3 value:book{id=3, name= ' Java algorithm '}

Gson Fromjson () usage

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.