First, let’s talk about a simpler example (I won’t talk about the simplest one, there are many online) to help beginners understand how to use Gson:
For example, we want to parse a Json like this:
String json = {"a":"100", "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 uses the form of an inner class, which 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; } }
Many times people don’t know how to define this bean.A few points to note here:
1. The internally nested classes must be static, otherwise the parsing will cause errors;
2. The attribute name in the class must be exactly the same as the Key in the Json field;
3. The internal nested part enclosed with [] is a List, so it is defined as public List<B> b, while only {} nested is defined as public C c,
For details, you can understand by looking at the Json string. If you don’t understand, we can communicate with each other. I am also a newbie in development!
Gson gson = new Gson(); type = new TypeToken<JsonBean>() {}.getType(); JsonBean jsonBean = (json, type);
Then it is very simple to get the data, just get it in jsonBean!
If the Json that needs to be parsed has many layers nested, you can also define a bean that nests many layers of inner classes, and you need to carefully define it with the Json field.
The above simple method for Android to use Gson to parse nested multi-layer Json is all the content I share with you. I hope you can give you a reference and I hope you can support me more.