1. The string JSON format obtained on the network is converted to object fetch data:
Required Package: Gson
Maven dependencies:
1 <!--Https://mvnrepository.com/artifact/com.google.code.gson/gson -2 <Dependency>3 <groupId>Com.google.code.gson</groupId>4 <Artifactid>Gson</Artifactid>5 <version>2.8.0</version>6 </Dependency>
Specific implementation:
1 Public Static string Stingtojson (String Result, string param) {2 New Jsonparser (); 3 jsonelement element = jsonparser.parse (Result); 4 Jsonobject object = element.getasjsonobject (); 5 String result = object.get (param). getasstring (); 6 return result; 7 }
Description
This parsing process I was to take a detour, because the method is not familiar, looking for tutorials everywhere, not fruit. At that time will report ClassCastException's mistake, then looked the official document only then discovers the clue.
Official Document Address: http://tool.oschina.net/apidocs/apidoc?api=gson2.2.2
where the 3rd line of code gets the element can be converted to several objects, but, where the Jsonarray in the code does not error, there is a Isjsonarray () method, you can add a judgement in advance, so you can completely avoid the error.
"About nesting"
There is a layer of this in the JSON data.
1 Public Static voidMain (string[] args) {2Loginresult = Loginpost ("Xtadmin", "1");3Jsonparser parser =NewJsonparser ();4jsonelement element =Parser.parse (loginresult);5 if(Element.isjsonobject ()) {6Jsonobject Jsonobject =Element.getasjsonobject ();7String string = Jsonobject.get ("Result"). getasstring ();8 System.out.println (string);9 jsonelement jsonelement = jsonobject.get ("entity"); Ten Jsonobject object = jsonelement.getasjsonobject (); One String token = object.get ("token"). getasstring (); A System.out.println (token); - } -}
9-11 of these lines is to retrieve the object again, then re-fetch the value.
JSON data obtained by string on "Gson" Web page converted to object