Jsonobject and Gson parsing JSON data in detail (GO)

Source: Internet
Author: User

reprint: http://www.jianshu.com/p/f99de3ec0636Click here to enter: From zero rapid build App series Catalog Map Point this entry: UI Programming Series Catalog Map Point this entry: Four Components series catalog map Point this entry: Data network and thread family directory map This section routines: Willflowjson. Introduction to JSON

We have already mastered the XML format data parsing, then we have to learn how to parse the JSON format of data, before we learn, we first make a simple comparison.

XML vs. JSON:
  • The data readability of JSON and XML is basically the same
  • JSON and XML also have rich parsing tools.
  • JSON is a small volume of data relative to XML
  • JSON interacts more easily with JavaScript
  • JSON is less descriptive of data than XML
  • JSON is much faster than XML

In short, the main advantage of JSON over XML is that it is smaller and can be used to save traffic when it travels over the network. The downside, however, is that it is less semantic and does not look as intuitive as XML.

(1) Format specification for JSON

Like protocols, JSON has a set of specifications, after all, both the server and the client are generally passing data through a JSON string.

It has the following syntax rules:

  • The data is in the "name/value" pair;
  • Data is separated by commas;
  • Curly braces Save the object;
  • Square brackets Save the array;
(2) sample writing format for JSON data
[    { "id":"1","name":"WGH","age":"18" },    { "id":"2","name":"WillFlow","age":"16"  }]
(3) JSON validation tool

In addition to parsing JSON, we can also join the JSON itself, of course, if you spell a JSON string and do not know right, you can use the Verification tool for verification, such as: Click here, and then put the JSON string of their own stitching up, you can verify the correct or not.

(4) The JSON parsing class provided by Android to us

The APIs for these JSON parsing classes exist under the Org.json package, and the classes we use have the following:

    • Jsonobject:json object, you can complete the conversion of JSON string to Java object
    • Jsonarray:json array to convert JSON strings to Java collections or objects
    • Jsonstringer:json text Build class, this class can help to create JSON text quickly and conveniently, each jsonstringer entity can only correspond to create a JSON text
    • Jsontokener:json Parsing class
    • Jsonexception:json exception
Second, using Jsonobject parsing JSON format data first define a JSON string constant in Mainactivity, the code is as follows:
    private static final String JSON = "[\n" +            "  {\"id\":\"1\",\"version\":\"1.5\",\"name\":\"Apple\"},\n" +            "  {\"id\":\"2\",\"version\":\"1.6\",\"name\":\"WillFlow\"},\n" +            "  {\"id\":\"3\",\"version\":\"1.7\",\"name\":\"WGH\"}\n" +            "]";

So we've got the JSON-formatted data ready and we're going to start parsing the data in the Android program.

Modify the code in the mainactivity as follows:
  @Override protected void onCreate (Bundle savedinstancestate) {Super.oncre        Ate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Parsejsonwithjsonobject (JSON); } private void Parsejsonwithjsonobject (String jsondata) {try {Jsonarray Jsonarray = new Jsonarray (j            Sondata);                for (int i = 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.I (TAG, "ID:" + ID);                LOG.I (TAG, "name:" + name);                LOG.I (TAG, "version:" + version);            LOG.I (TAG, "————————————————————");        }} catch (Exception e) {e.printstacktrace (); }    }

As you can see, the code that parses the JSON is really very simple, because we define a JSON array, so here we first pass the data into a Jsonarray object, and then iterate through the Jsonarray, and each element that is removed from it is a jsonobject Object, and each Jsonobject object contains the data for the ID, name, and version. Next, just call the GetString () method to remove the data and print it out.

Compile run View log count out
III. parsing JSON format data with Gson

How you think it's easy to use Jsonobject to parse JSON data, you're just too easy to be satisfied. Google provides the Gson open Source Library can make it easy to parse JSON data to the point that you do not dare to imagine, then we must not miss this learning opportunity.

First, configure the following dependencies in Gradle:
dependencies {    ......    compile ‘com.google.code.gson:gson:2.8.1‘}

This time the Gson frame is loaded, and we need to sync it manually.

If you don't have the Gson plugin installed in your Android Studio, you can install it:

Restart Android Studio when you're done.

So what is the magic of the Gson library? In fact, it is mainly the ability to automatically map a JSON-formatted string into an object, so that we do not need to manually write code to parse, such as a JSON-formatted data as follows:

{"name":"Tom","age":20}

Then we can define a person class and add the name and age fields, and then simply call the following code to automatically parse the JSON data into a person object:

Gson gson = new Gson();Person person = gson.fromJson(jsonData, Person.class);

If it is a bit of a hassle to parse a JSON array, we need to pass the expected parsed data type into the Fromjson () method with TypeToken, as shown here:

List<Person> people = gson.fromJson(jsonData, new TypeToken<List<Person>>(){}.getType());

The basic usage is this, let's really try it out here.

Here we first prepare the JSON raw data that needs to be parsed:
[  {"id":"1","version":"1.5","name":"Apple"},  {"id":"2","version":"1.6","name":"WillFlow"},  {"id":"3","version":"1.7","name":"WGH"}]
Then create a new Appbean class for the definition of the data specification:
/** * Created by   : WGH. */public class AppBean {}
Then "ALT + Insert" anywhere in the class, then select "Gson Format" or use the shortcut "ALT + S"
Then you will see this interface, and then paste the original JSON data we just pasted in and click OK:
Continue clicking OK and you will find that the Appbean has become this way:
/** * Created by   : WGH. */public class AppBean {    /**     * id : 1     * version : 1.5     * name : Apple     */    private String id;    private String version;    private String name;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getVersion() {        return version;    }    public void setVersion(String version) {        this.version = version;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

This is a data class that contains the three fields of ID, name, and version, and the key value of the member variable and the JSON raw data is exactly the same (this is especially important, which is necessary to use Gson parsing).

Finally, this method is defined in Mainacitivyt:
    private void parseByGSON(String jsonData) {        Gson gson = new Gson();        List<AppBean> appList = gson.fromJson(jsonData, new TypeToken<List<AppBean>>() {}.getType());        for (AppBean app : appList) {            Log.i(TAG, "id : " + app.getId());            Log.i(TAG, "name : " + app.getName());            Log.i(TAG, "version : " + app.getVersion());            Log.i(TAG, "————————————————————");        }    }

Then the output can be called.

Compile run View log output

In this way we will be XML and JSON these two data formats most commonly used in several analytic methods are finished, in the analysis of network data, we have successfully graduated.



Jsonobject and Gson parsing JSON data in detail (GO)

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.