Android Jsonoject and Gson two ways to parse JSON

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.