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