1. What is JSON data
JSON (JavaScript Object Notation) is a lightweight data exchange format: key:value
format.
JSON uses a completely language-independent text format. These features make JSON an ideal data exchange language. Easy for humans to read and write, and easy for machines to parse and generate.
2. JSON string
JSON string is a string string in JSON format, that is, JSON string is also a string type, but this string is There is a format, that is, a map-like format [key:value].
The key of JSON string must be a string (numeric values can also be stored, but the values are still String when they are stored and taken out);
The value of a JSON string can be: number (integer or floating point number), string (in double quotes), array (in square brackets), object (in curly brackets), true/false/null.
3. Back-end JSONObject object
JSONObject is a data structure that can be understood as a data structure in JSON format (key-value structure ), Similar to map, you can use the put method to add elements to the JSONObject object. JSONObject can be easily converted into a string, and other objects can also be easily converted into JSONObject objects.
(1) Generate JSONObject
JSONObject zhangsan = new JSONObject(); try { //添加 zhangsan.put("name", "张三"); zhangsan.put("age", 18.4); zhangsan.put("birthday", "1900-20-03"); zhangsan.put("majar", new String[] {"哈哈","嘿嘿"}); zhangsan.put("null", null); zhangsan.put("house", false); System.out.println(zhangsan.toString()); } catch (JSONException e) { e.printStackTrace(); }
through native (2) Generate
HashMap<String, Object> zhangsan = new HashMap<>(); zhangsan.put("name", "张三"); zhangsan.put("age", 18.4); zhangsan.put("birthday", "1900-20-03"); zhangsan.put("majar", new String[] {"哈哈","嘿嘿"}); zhangsan.put("null", null); zhangsan.put("house", false); System.out.println(new JSONObject(zhangsan).toString());
through hashMap data structure (3) Generate
Student student = new Student(); student.setId(1); student.setAge("20"); student.setName("张三"); // 生成 JSONObject System.out.println(JSON.toJSON(student));
through JavaBean (4 ) JSON string and JSONObject conversion
String studentString = "{\"id\":1,\"age\":2,\"name\":\"zhang\"}"; //JSON字符串转换成 JSONObject JSONObject jsonObject1 = JSONObject.parseObject(stuString); System.out.println(jsonObject1);
4, front-end JSON string and Javascript object comparison
5, Basic structure
Two structures of JSON:
(1) A collection of name/value pairs. In different languages, it is understood as an object, a record, a struct, a dictionary, a hash table, a keyed list, or an associative array. array).
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
(2) An ordered list of values. In most languages, it is understood as an array.
{ "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"}, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ]}
5. JSON format application
(1) Assign JSON data to variables
For example, you can create a new Javascript variable, and then Directly assign the data string in JSON format to it:
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }
(2) Access data
After putting the above array into a Javascript variable, you can easily access it. In fact, accessing array elements is simply done using dot notation. So, to access the last name of the first entry in the programmers list, just use the following
code in JavaScript:
people.programmers[0].lastName;
(3) Modify the JSON data
Just as data can be accessed with periods and brackets, data can also be easily modified in the same way
people.musicians[1].lastName = "Rachmaninov";
(4) Convert strings
Any JSONObject and Javascript object can be converted to JSON Text can also be inversely converted.
1. Jackson class
(1) maven introduces dependencies
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.9</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.9</version> </dependency>
(2) Class library function usage
@RequestMapping(value="/returnJson") //@ResponseBody注解将JSON数据写入响应流中返回到前端 @ResponseBody public String returnJson(){ ObjectMapper objectMapper=new ObjectMapper(); Student student=new Student(); //writeValueAsString()函数将对象转换为JSON字符串 return objectMapper.writeValueAsString(student); }
2, FastJson class library
(1) Maven introduces dependencies
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.4</version> </dependency>
(2) The difference in details when the class library function uses
// 将 JSON 字符串反序列化成 JavaBean public static final Object parse(String text); // 将 JSON 字符串反序列化成 JSONObject public static final JSONObject parseObject(String text); // 将 JSON 字符串反序列化成 JavaBean 或 JSONObject public static final <T> T parseObject(String text, Class<T> clazz); // 将 JSON 字符串反序列化成JSONObject 的数组 public static final JSONArray parseArray(String text); // 将 JSON 字符串反序列化成 JavaBean 的数组 public static final <T> List<T> parseArray(String text, Class<T> clazz); // 将 Java 对象序列化为JSON 字符串 public static final String toJSONString(Object object); // 将 Java 对象序列化为带格式的 JSON 字符串 public static final String toJSONString(Object object, boolean prettyFormat); //将 JavaBean 转换为 JSONObject 或者 JSONArray。 public static final Object toJSON(Object javaObject);
parse() and parseObject() for deserialization is: parse() will identify and call the setter method of the target class; parseObject() will The return value is converted into JSONObject, and JSON.toJSON(obj) is executed, that is, the JavaBean is converted into JSONObject. Therefore, during the processing, the getter method of the deserialization target class is called to assign the parameters to the JSONObject.
3. Use the @RestController annotation
@RestController is a combined annotation of @ResponseBody and @Controller.
1) @Controller is used to respond to the page. If it is a string type method, springmvc will jump to the corresponding page (view).
2) @ResponseBody is used to respond to data. If it is an object type or Map type method, springmvc will convert the result object into json format and output it to the front end. (After converting the object returned by the controller method into the specified format through an appropriate converter, it is written to the body area of the response object)
3) The @RestController annotation will cause springmvc to The returned object or Map is automatically converted to json and returned to the front end (the underlying default is to use jsckson to implement data format conversion).
@RequestMapping(value="/returnJson") @ResponseBody public Student returnJson(){ Student student=new Student(); student.setName("林俊杰"); student.setBirth(new Date(1996-03-15)); student.setPassword("123456"); String[] lan= {"Java","Python"}; student.setLanguage(lan); return student; }
1. Use JSON library
(1 ) Javascript object and json string conversion
var jsonVar = {key: value} //将JS对象转换为JSON字符串 var jsonString = JSON.stringify(jsonVar) //将JSON字符串转换为JSON对象 var jsonObject = JSON.parse(jsonString)
(2) Javascript array and json string conversion
var jsonVar = [value1,..,value] //将JS数组转换为JSON字符串 var jsonString = JSON.stringify(jsonVar) //将JSON字符串转换为数组对象 var jsonObject = JSON.parse(jsonString)
2, Javascript comes with methods
The eval () function that comes with Javascript can convert json data into Javascript objects.
var json = '{"name":"James"}'; var obj = eval( '(' + json + ')' ); //注意需要在json字符外包裹一对小括号 alert( obj.name );
3、jQuery 的自带方法
jQuery 中可以使用 $.parseJSON(json) 来将 json 转换为 Javascript 对象。
var json = '{"name":"James"}'; var obj = $.parseJSON(json); alert( obj.name );
4、使用 jquery.json 插件
该插件提供了 4 个函数,用于解析和反解析 json,具体如下:
(1)toJSON:将 Javascript 的 object、number、string 或 array 转换成 JSON 数据。
(2)evalJSON:把 JSON 格式数据转换成 Javascript 对象,速度很快,不过这点速度微不足道。
(3)secureEvalJSON:把 JSON 转换成 Javascript 对象,但是转换之前会检查被转换的数据是否是 JSON 格式的。
(4)quoteString:在字符串两端添加引号,并智能转义(跳过)任何引号,反斜杠,或控制字符。
(注意:需要和 jQuery 核心库结合使用)
var obj = {"plugin":"jquery-json","version":2.4}; //json = '{"plugin":"jquery-json","version":2.4}' var json = $.toJSON( obj ); // 得到name值为:"jquery-json" var name = $.evalJSON( json ).plugin; // 得到version值为:2.4 var version = $.evalJSON( json ).version;
The above is the detailed content of What is the JSON transmission method for Java front-end and back-end?. For more information, please follow other related articles on the PHP Chinese website!