Android uses Gson to parse the simple method of nesting multiple layers of JSON _android

Source: Internet
Author: User

First of all, let's start with a simpler example (the simplest I don't speak, a lot on the web) to help beginners understand how gson is used:

For example, we're going to parse one of these JSON:

String json = {"A": "M",
"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 takes the form of an inner class and looks 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;
     }

Most of the time you don't know what the bean is supposed to be, and there are a few things to note:

1, the internal nested class must be static, otherwise parsing will be wrong;

2, the property name inside the class must be the same as the key in the JSON field;

3, the internal nesting with [] enclosed part is a List, so defined as public list<b> B, and only {} nested is defined as public C C,

The specific people control the JSON string to see understand, do not understand we can communicate with each other, I am also a novice development!

 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 to take it!

If you need to parse a JSON that has nested many layers, you can also define a bean that is nested within many layers of the class, and you need to be careful about defining it against the JSON field.

The above Android uses Gson to parse the nested multilayer JSON the simple method is the small series to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.

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.