The main advantage over Xml,json is that it is smaller and can be used to save traffic when it travels over the network. But the downside is that it's less semantic and not as intuitive as XML.
JSON format: {"name_a": "Value_a", "Name_b": "Value_b"}
Expression: name_a = Value_a; Name_b = Value_b;
I will parse the following JSON data:
[{"id": "5", "Version": "5.5", "name": "Angry Bird"},{"id": "6", "Version": "7.0", "name": "Temple Escape"},{"id": "7", "Version": "3.5", "Name": "Defend Radish"}]
The code is as follows:
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 name= jsonobject.getstring ("name"); String version= jsonobject.getstring ("Version"); LOG.D ("Woider", "ID is" +ID); LOG.D ("Woider", "name is" +name); LOG.D ("Woider", "version is" +version); } } Catch(Exception e) {e.printstacktrace (); } }
first get an array of JSON elements : Jsonarray Jsonarray = new Jsonarray (jsondata);
Next loop gets each element : jsonobject jsonobject = jsonarray.getjsonobject (index);
each cycle holds the value corresponding to the name : String name = jsonobject.getstring ("name");
====================== using gson========================
Gson is an API provided by Google, which is basically the ability to automatically map a JSON-formatted string into an object , eliminating the need for manual encoding for parsing.
However, Gson is not added to the official Android API, so if you need to use this feature, you must add a Gson jar package to your project.
The first thing to do is to create a class that holds the data in the JSON, then instantiate the Gson object and get a collection of JSON objects through the Fromjson () method.
Private void Parsejsonwithgson (String jsondata) { new Gson (); ListNew typetoken<list<app>>() { }.gettype ()); for (App app:applist) { log.d ("Woider", "ID is" + App.getid ()); LOG.D ("Woider", "name is" + app.getname ()); LOG.D ("Woider", "version is" + app.getversion ()); } }
Finally, fill up the run:
Android parsing JSON format data