Android uses Gson to parse nested layers of JSON

Source: Internet
Author: User

First of all, a simple example (the simplest I do not speak, many online), to help beginners understand how to use Gson:
For example, we want to parse one of the following JSON:
String json = {"A": "+", "B": [{"B1": "B_value1", "B2": "B_value2"},{"B1": "B_value1", "B2": "B_value2"}], "C": {"C1": "C_ Value1 "," C2 ":" C_value2 "}}
First we need to define a serialized bean, which, in the form of an inner class, will look clearer:
public class Jsonbean {
Public String A;
Public list<b> B;
public c C;

public static class B {
Public String B1;
Public String B2;
}

public static class C {
Public String C1;
public String C2;
}
}
Many times people do not know how this bean is defined, which should be noted in several points:
1, the internal nested class must be static, otherwise the parsing will be wrong;
2. The attribute name inside the class must be identical to the key inside the JSON field;
3, internal nested in the [] part is a List, so defined as public list<b> B, and only with {} nested is defined as the public C C,
Specific people against the JSON string to see the understanding, do not understand that we can communicate with each other, I am also a novice developer!
Gson Gson = new Gson ();
Java.lang.reflect.Type Type = new typetoken<jsonbean> () {}.gettype ();
Jsonbean Jsonbean = Gson.fromjson (JSON, type);
Then want to take the data is very simple, directly in the jsonbean inside to take it!
If you need to parse the JSON nested a lot of layers, you can also define a nested many layers of internal classes of beans, you need to carefully control the JSON field to define OH.

Android uses Gson to parse nested layers of JSON

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.