GSON parses JSON and gsonjson
The GSON open-source library provided by Google makes parsing JSON data easy to imagine. To use GSON, you must add a GSON jar package to the project. First, download the GSON resource package.
Address: https://github.com/google/gson
GSON is powerful in that it can automatically map a json string into an object, so that we do not need to write code for parsing. For example, data in json format is as follows:
{"Name": "tom", "age": "20 "}
Then we can define a Person class and add the name and age fields. Then, simply call the following code to automatically parse json data into a Person object:
Gson gson = new Gson ();
Person person = gson. fromJson (jsonData, Person. class );
If you want to parse a json array, it will be a little troublesome. We need to use TypeToken to pass the expected data type to fromJson (), as shown below:
List <Person> people = gson. fromJson (jsonData, new TypeToken <List <Person> () {}. getType ());
Well, the basic usage is like this. Let's try it. First add an App class and add the fields id, name, and version, as shown below::
package com.jack.networktest; public class App { private String id; private String name; private String version; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
Parsing Code:
// Use the JSONWithGSON (String jsonData) method to parse the private void parseJSONWithGSON (String jsonData) {Gson gson = new Gson (); List <App> appList = gson. fromJson (jsonData, new TypeToken <List <App> (){}. getType (); for (App app: appList) {Log. d ("MainActivity", "id is" + app. getId (); Log. d ("MainActivity", "name is" + app. getName (); Log. d ("MainActivity", "version is" + app. getVersion ());}}