The JSON file is as follows:
Converts the retrieved JSON data to a string form
New okhttpclient (); New Request.builder () . URL ("Http://10.0.2.2/get_data.json") . Build (); =Client.newcall (Request). Execute (); = Response.body (). String ();
Parse by Jsonobject: Converts the obtained string into a JSON array, and loops through the array.
Private voidParsejsonwithjsonobject (String jsondata) {Try{Jsonarray Jsonarray=NewJsonarray (Jsondata); for(intI=0;i<jsonarray.length (); i++) {Jsonobject jsonobject=Jsonarray.getjsonobject (i); String ID= jsonobject.getstring ("id"); String version= jsonobject.getstring ("Version"); String name= jsonobject.getstring ("name"); LOG.I ("Jsonobject", "ID is:" +ID); LOG.I ("Jsonobject", "version is:" +version); LOG.I ("Jsonobject", "name is:" +name); } }Catch(Exception e) {e.printstacktrace (); } }
In Gson way:
First, the corresponding class is built according to the JSON file:
Public classapp{PrivateString ID; PrivateString version; PrivateString name; PublicString getId () {returnID; } Public voidsetId (String id) { This. ID =ID; } PublicString getversion () {returnversion; } Public voidsetversion (String version) { This. Version =version; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; }}
Then, create a new Gson object, use TypeToken to turn data into a list and pass the list to the Fromjson method
Private void Parsejsonwithgson (String jsondata) { new Gson (); List<App> applist = Gson.fromjson (Jsondata,new typetoken<list<app>>() {}. GetType ()); for (App app:applist) { log.i ("Gson", "ID is:" +App.getid ()); LOG.I ("Gson", "version is:" +app.getversion ()); LOG.I ("Gson", "name is:" +app.getname ()); } }
Android Jsonoject and Gson two ways to parse JSON