First, the JSON data format is divided into three types: Array, object, array object blending
Array format:
{"ASD", "Qwe", "Ffe"}
Object Format:
{"A": 1, "B": 2, "C": 3} Note Write code to add escape character \ To get double quotation marks: \ "
Array Object Blending format:
{ [
{"A": 1, "B": 2},
{"C": 3, "D": 4}
]
[
....
]
}
Using Gson parsing JSON, if there is an object format, you need to use JavaBean to implement, the code is as follows:
1 // Object converted to 2 String str = "{\" data\ ": [{\" name\ ": Sad,\" age\ ": 18},{\" name \ ":d dd,\" age\ ":
3 gson g =
new
Gson ();
4 listperson list = G.fromjson (Str,listperson.
Class
5 for ( Person P:list.getlist ()) { 6 System.out.println ("Age:" +p.getage () + "n Ame: "+p.getname ()); 7 }
Because it is a mixed format of array + objects and requires two JavaBean, the following is the code for the JavaBean aspect:
1 Static classperson{2 PublicString name;3 Public intAge ;4 PublicString GetName () {5 returnname;6 }7 8 Public voidsetName (String name) {9 This. Name =name;Ten } One A Public intGetage () { - returnAge ; - } the - Public voidSetage (intAge ) { - This. Age =Age ; - } + } - + Static classlistperson{ AList<person>data; at - PublicList<person>getList () { - returndata; - } - - Public voidSetlist (list<person>list) { in This. data =list; - } to}
Note : The first name to correspond, because in JSON my array name is data, so in JavaBean what variable name is also data, the following is a different name, the console output information:
Java.lang.NullPointerException
Next, the object is converted to the JSON data format, with the following code:
1 New Hashmap<>(); 2 Map.put ("A", 1); 3 Map.put ("B", 2); 4 Map.put ("C", 3); 5 System.out.println (new Gson (). ToJson (map));
If you are using JSON data in an array format, to get the type of a generic class, a method is provided in Gson
New Typetoken<list<map.entry<string,string>>> () {}.gettype ()
Reference Link: https://www.jianshu.com/p/e740196225a4
Application of JSON data format and Gson parsing JSON