android parses JSON data
- 2021-06-28 09:43:20
- OfStack
Use of JSONObject
1.Use of JSON objects:
String content = "{'username': 'linux', 'password': '123456'}";
JSONObject jsonObject = new JSONObject(content);
String username = jsonObject.getString("username");
String password = jsonObject.getString("password");
2.Use of the JSON array:
String jsonContent = "[{'user': ' Liu Li ', 'age': 21, 'femal': true}, "
+ "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object.getString("user") + " ");
System.out.print(object.getInt("age") + " ");
System.out.print(object.getBoolean("femal") + " ");
System.out.println();
}
3. JSON array mixed with JSON object
String jsonString = "[{'user': 'tomhu', 'age': 21, " + "'info': {'adress': 'hubai', 'sex': 'femal'}}, "
+ "{'user': 'chen', 'age': 20, " + "'info': {'adress': 'hunan', 'sex': 'male'}}]";
JSONArray jsonArrays = new JSONArray(jsonString);
for (int i = 0; i < jsonArrays.length(); i++) {
JSONObject objects = jsonArrays.getJSONObject(i);
System.out.print(objects.getString("user") + " ");
System.out.print(objects.getInt("age") + " ");
System.out.print(objects.getJSONObject("info").getString("adress") + " ");
System.out.print(objects.getJSONObject("info").getString("sex") + " ");
System.out.println();
}
4. Storing objects in the JSON array
Person person = new Person();
person.setUsername("linux" );
person.setPassword("123456" );
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, person );
jsonArray.put(1, "I love you" );
// String username = jsonArray.getJSONObject(0).getString("username"); Wrong Writing
Person user = (Person) jsonArray.get(0);
System.out.println("username: " + user.getUsername());
Principle of JSONObject
Storage and Removal of JsonObject
1.JSONObject maintains an LinkedHashMap. When an JSONObject without parameters is generated, essentially an Map is initialized:
private final LinkedHashMap<String, Object> nameValuePairs;
public JSONObject() {
nameValuePairs = new LinkedHashMap<String, Object>();
}
2. When JSONObject adds data, essentially store the key-value pair method of the data in Map as described above:
public JSONObject put(String name, boolean value) throws JSONException {
nameValuePairs.put(checkName(name), value);
return this;
}
3. From JSONObject, it is easy to imagine that from Map:
public String getString(String name) throws JSONException {
Object object = get(name); // get() The method is to execute Object result = nameValuePairs.get(name);
String result = JSON.toString(object);
if (result == null) {
throw JSON.typeMismatch(name, object, "String");
}
return result;
}
Resolution of JsonObject
1.JsonObject also has a constructor with parameters: it is common to pass an String-type parameter
public JSONObject(String json) throws JSONException {
this(new JSONTokener(json));
}
2. Follow-up found that the main implementation is JSONTokener's nextValue() method, in which data is mainly parsed;
public Object nextValue() throws JSONException {
int c = nextCleanInternal();
switch (c) {
case -1:
throw syntaxError("End of input");
case '{':
return readObject();
case '[':
return readArray();
case '\'':
case '"':
return nextString((char) c);
default:
pos--;
return readLiteral();
}
}
In the nextCleanInternal method, it parses characters from beginning to end and does some processing on a few characters.Examples include spaces, line breaks, escape characters, and so on!
When parsing to [means starting a read on an object, when parsing to {means reading on an array
3. In the readObject method, the nextCleanInternal () method is still called to get the parsed characters one by one, down to parse to}. Paste the important code below
int first = nextCleanInternal(); // Resolved Character
if (first == '}') {
return result;
} else if (first != -1) {
pos--;
}
.......
while (true) {
Object name = nextValue(); // Resolve to Key
int separator = nextCleanInternal();
if (separator != ':' && separator != '=') {
throw syntaxError("Expected ':' after " + name);
}
if (pos < in.length() && in.charAt(pos) == '>') {
pos++;
}
result.put((String) name, nextValue()); // Store the resolved key-value pairs in map Among
switch (nextCleanInternal()) {
case '}':
return result;
case ';':
case ',':
continue;
default:
throw syntaxError("Unterminated object");
}
}
4.The nextValue method is critical, it flows most of the work of parsing!There is an readLiteral method in nextValue that handles a number of types and yields results after parsing:
String jsonContent = "[{'user': ' Liu Li ', 'age': 21, 'femal': true}, "
+ "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object.getString("user") + " ");
System.out.print(object.getInt("age") + " ");
System.out.print(object.getBoolean("femal") + " ");
System.out.println();
}
0
5. As for JSONArray, the process is the same as JsonObject, which maintains an List:
String jsonContent = "[{'user': ' Liu Li ', 'age': 21, 'femal': true}, "
+ "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object.getString("user") + " ");
System.out.print(object.getInt("age") + " ");
System.out.print(object.getBoolean("femal") + " ");
System.out.println();
}
1
Use of Gson
1. We add an Person class to the test to facilitate the test:
String jsonContent = "[{'user': ' Liu Li ', 'age': 21, 'femal': true}, "
+ "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object.getString("user") + " ");
System.out.print(object.getInt("age") + " ");
System.out.print(object.getBoolean("femal") + " ");
System.out.println();
}
2
2.gson Converts Objects to JSON Format
Gson gson = new Gson();
Person person = new Person();
person.setName("linux");
person.setAge(23);
String str = gson.toJson(person);
System.out.println(str);
Print results: {"name": "linux", "age": 23}
3.gson parses json format into objects
String jsonContent = "[{'user': ' Liu Li ', 'age': 21, 'femal': true}, "
+ "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object.getString("user") + " ");
System.out.print(object.getInt("age") + " ");
System.out.print(object.getBoolean("femal") + " ");
System.out.println();
}
4
Print results: Liu Li, 19
4.gson parses the List object into Json format:
String jsonContent = "[{'user': ' Liu Li ', 'age': 21, 'femal': true}, "
+ "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object.getString("user") + " ");
System.out.print(object.getInt("age") + " ");
System.out.print(object.getBoolean("femal") + " ");
System.out.println();
}
5
Print results: [{"name": "name0", "age": 0}, {"name": "name1", "age": 5}]
5.gson parses the Json format into an List object:
String jsonContent = "[{'user': ' Liu Li ', 'age': 21, 'femal': true}, "
+ "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object.getString("user") + " ");
System.out.print(object.getInt("age") + " ");
System.out.print(object.getBoolean("femal") + " ");
System.out.println();
}
6
Print result: name: linux age: 10 name: huhx age: 22