What is JSON and how to solve the problem of JSON garbled code

1. What is JSON?

  • JSON (JavaScript object notation) is a lightweight data exchange format, which is widely used at present.

  • Data is stored and represented in a text format completely independent of the programming language.

  • The concise and clear hierarchy makes JSON an ideal data exchange language.

  • It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

         In the JavaScript language, everything is an object. Therefore, any type supported by JavaScript can be represented by JSON, such as string, number, object, array, etc. Look at his requirements and syntax format:

  • Objects are represented as key value pairs, and data is separated by commas

  • Curly braces save objects

  • Square brackets hold the array

         JSON key value pairs are a way to save JavaScript objects, and the writing method is similar to that of JavaScript objects. The key name in the key / value pair combination is written in front and wrapped in double quotation marks "", separated by colon: and then followed by the value:

{"name": "QinJiang"}
{"age": "3"}
{"sex":   "Male"}

          JSON is a string representation of JavaScript objects. It uses text to represent the information of a JS object, which is essentially a string.

         JSON and JavaScript objects interoperate

         To convert from a JSON string to a JavaScript object, use the JSON.parse() method:

var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//The result is {a: 'Hello', b: 'World'}

        To convert from a JavaScript object to a JSON string, use the JSON.stringify() method:

var json = JSON.stringify({a: 'Hello', b: 'World'});
//The result is' {"a": "Hello", "b": "World"} '

2. Use the Controller of spring MVC to return JSON data:

         Jackson should be a better json parsing tool at present

         Of course, there are more than one tool, such as Alibaba's fastjson and so on.

       1. We use Jackson here. To use Jackson, we need to import its jar package;

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>

        2. Add StringHttpMessageConverter in springmvc.xml to solve JSON garbled code

 <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

        3. Controller

             Use @ RestController directly on the class. In this way, all the methods in it will only return json strings. There is no need to add @ ResponseBody to each one! We usually use it in front and back-end separation development

@Controller
public class UserController {
    @ResponseBody//He will not go to the view parser and will directly return a string
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
        //Create an object mapper for jackson to parse the data
        ObjectMapper mapper = new ObjectMapper();
        //Create an object
        User user=new User("Rowling",20,"male");
        //Parse our object into json format
        String str = mapper.writeValueAsString(user);
        //Due to the @ ResponseBody annotation, str will be converted to json format and returned here; Very convenient
        return str;
    }
}

3,FastJson

         fastjson.jar is a package developed by Alibaba for Java development. It can easily realize the conversion between json objects and JavaBean objects, between JavaBean objects and json strings, and between json objects and json strings. There are many conversion methods to implement json, and the final implementation results are the same.

        Code test tool class:

package com.kuang.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuang.pojo.User;
import java.util.ArrayList;
import java.util.List;
public class FastJsonDemo {
   public static void main(String[] args) {
       //Create an object
       User user1 = new User("Rollin 1", 23, "male");
       User user2 = new User("Rollin 2", 23, "male");
       User user3 = new User("Rollin 3", 23, "male");
       User user4 = new User("Rollin 4", 23, "male");
       List<User> list = new ArrayList<User>();
       list.add(user1);
       list.add(user2);
       list.add(user3);
       list.add(user4);
       System.out.println("*******Java Object rotation JSON character string*******");
       String str1 = JSON.toJSONString(list);
       System.out.println("JSON.toJSONString(list)==>"+str1);
       String str2 = JSON.toJSONString(user1);
       System.out.println("JSON.toJSONString(user1)==>"+str2);

       System.out.println("\n****** JSON String conversion Java object*******");
       User jp_user1=JSON.parseObject(str2,User.class);
       System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);

       System.out.println("\n****** Java Object rotation JSON object ******");
       JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
       System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));

       System.out.println("\n****** JSON Object rotation Java object ******");
       User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
       System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
  }
}

Keywords: Javascript html5 JSON html

Added by kurdishvoice on Sat, 02 Oct 2021 03:09:10 +0300