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.