1. json data type
type | describe |
---|---|
Number | Digital type |
String | String type |
Boolean | Boolean type |
Array | array |
Object | object |
null | Null value |
(1) json does not distinguish between integer and decimal types, but uses Number to store numbers.
(2) Array represents an array, enclosed in brackets "[]", separated by commas between elements, which can be of any type.
(3) Object represents objects, similar to the structure in C language, enclosed in curly brackets "{}", whose elements are required to be key-value pairs, key must be String type, and value can be arbitrary type. The mapping relationship between key and value is represented by ":", and the elements are separated by commas.
(4) String, Boolean, null are the same as those in Java, which is not discussed here.
2. Building json
To use JSONObject, you need to refer to the org.json package. It is recommended to refer to it through maven. If you don't use maven, you can refer to this article for building maven projects. "Building Maven Project with Eclipse" (step-by-step) To quote json, refer to this article "maven Introduces Various Versions of json".
Warm Tip: When I build the maven project, I often failed to create it. I searched it online for a long time, but I still can't make it. Later, the scientific Internet was done. If you also failed to create it, you can try it.
2.1 Direct Construction
JSONObject obj = new JSONObject(); obj.put(key, value);
Direct construction means instantiating a JSONObject object directly, and then calling its put() method to write data. The first parameter of the put() method is the key value, which must be String type, and the second parameter is value, which can be boolean, double, int, long, Object, Map, Collection, etc. Of course, types like double and int are only in Java, and when written to json, the unification is stored in Number type.
Example:
import org.json.JSONObject; public class JSONObjectSample { public static void main(String[] args) { createJson(); } private static void createJson() { JSONObject obj = new JSONObject(); obj.put("name", "John"); obj.put("sex", "male"); obj.put("age", 22); obj.put("is_student", true); obj.put("hobbies", new String[] {"hiking", "swimming"}); //Calling the toString() method prints its contents directly System.out.println(obj.toString()); } }
The output results are as follows:
{"hobbies":["hiking","swimming"],"sex":"male","name":"John","is_student":true,"age":22}
As you can see here, in order to compress the size for more efficient transmission, json removes all blank characters such as spaces, newlines, etc. If you want to see the content intuitively, you can use some online json parsers, such as: http://www.jsoneditoronline.org/
2.2 Build with HashMap
Using HashMap to build json actually creates a HashMap object and packages the data in it, then passes it in as a parameter when creating JSONObject.
Example:
public class JSONObjectSample { public static void main(String[] args) { createJsonByMap(); } private static void createJsonByMap() { Map<String, Object> data = new HashMap<String, Object>(); data.put("name", "John"); data.put("sex", "male"); data.put("age", 22); data.put("is_student", true); data.put("hobbies", new String[] {"hiking", "swimming"}); JSONObject obj = new JSONObject(data); System.out.println(obj.toString()); } }
2.3 Build with JavaBean
Compared with the first two methods, it is more common to use JavaBean to build json in actual development, because the code is more reusable.
Example:
JavaBean:
public class PersonInfo { private String name; private String sex; private int age; private boolean isStudent; private String[] hobbies; public void setName(String name) { this.name = name; } public void setSex(String sex) { this.sex = sex; } public void setAge(int age) { this.age = age; } public void setStudent(boolean isStudent) { this.isStudent = isStudent; } public void setHobbies(String[] hobbies) { this.hobbies = hobbies; } }
main:
import org.json.JSONObject; public class JSONObjectSample { public static void main(String[] args) { createJsonByJavaBean(); } private static void createJsonByJavaBean() { PersonInfo info = new PersonInfo(); info.setName("John"); info.setSex("male"); info.setAge(22); info.setStudent(true); info.setHobbies(new String[] {"hiking", "swimming"}); JSONObject obj = new JSONObject(info); System.out.println(obj); } }
3. Analyzing json
Parsing json is mainly a basic type such as Number, boolean, and array Array.
The parsing of the basic type directly calls the getXxx(key) method of the JSONObject object, getString(key) if the string is obtained, and getBoolean(key) if the Boolean value is obtained, and so on.
Array parsing is a bit cumbersome. You need to get a JSONArray object through the getJSONArray(key) method of the JSONObject object, and then call the get(i) method of the JSONArray object to get the array element, I is the index value.
Example:
First, create a json file under the project directory "src/main/java" for parsing.
demo.json:
{ "hobbies": [ "hiking", "swimming" ], "sex": "male", "name": "John", "is_student": true, "age": 22 }
Add commons-io dependency to pom.xml to facilitate file access using FileUtils:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.studying</groupId> <artifactId>myjson</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>myjson</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency> <!--Join pairs commons-io Dependence--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies> </project>
Main categories:
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.json.JSONArray; import org.json.JSONObject; public class JSONObjectSample { public static void main(String[] args) throws IOException { File file = new File("src/main/java/demo.json"); String content = FileUtils.readFileToString(file); //Analysis of Basic Types JSONObject obj = new JSONObject(content); System.out.println("name: " + obj.getString("name")); System.out.println("sex: " + obj.getString("sex")); System.out.println("age" + obj.getInt("age")); System.out.println("is_student" + obj.getBoolean("is_student")); //Analysis of Arrays JSONArray hobbies = obj.getJSONArray("hobbies"); System.out.println("hobbies: "); for (int i = 0; i < hobbies.length(); i++) { String s = (String) hobbies.get(i); System.out.println(s); } } }