JSON, which stands for JavaScript Object Notation, is now commonly used as the language for communicating between different programs. As a syntax rule for communication between machines, it becomes very important for programmers to master the parsing of JSON, which will help us communicate with programs.

A simple JSON example is as follows:

{
    "name":"Xiao Wang"."age":18."pengyou": ["Zhang"."Bill"."Two"."Mike", {"name":"Mustang Teacher"."info":"Running like a wild horse down the road of technical research."}]."heihei": {"name":"Long knife"."length":"40m"}}Copy the code

Here are three common parsing methods:

1 Gson

  • Convert the object to a JSON string
  1. The introduction of the JAR package

  2. Write the following code where you need to convert the JSON string:

String json = newGson().tojson (the object to convert);Copy the code

  • Convert a JSON string to an object
  1. The introduction of the JAR package

  2. Where you need to convert Java objects, write the following code

Object =newGson().fromjson (JSON string, object type.class);Copy the code

Case Demo:

public class Demo1 {
    public static void main(String[] args) {
        // Create a JSON object
        Gson gson = new Gson();
        / / convert json {" id ":" 100 ", "name" : "golden", "info", "planting apple"}
        Book book = new Book("100"."Golden apple"."Growing apples.");
        String s = gson.toJson(book);
        System.out.println(s);
        // json to a stringBook book1 = gson.fromJson(s, Book.class); System.out.println(book1); }}Copy the code

public static void main(String[] args) {
    // Create a JSON object
    Gson gson = new Gson();
    / / json string {" id ":" 100 ", "name" : "golden", "info", "planting apple", "page" : [" hoe grain to be noon for day ", "began sweating grain soils"]}
    HashMap data = gson.fromJson("{"id":"100","name":"The golden apples","info":"Planting apple","page": ["Hoe Hoe Day","Sweat dripped the soil"]}", HashMap.class);
    System.out.println(data.get("page"));
    // Arrays in JSON are converted to List collections
    System.out.println(data.get("page").getClass());

    List page = (List) data.get("page");
    System.out.println(page.get(1));
}
Copy the code

2 FastJson

  • Convert the object to a JSON string

Steps for converting JSON strings:

  1. The introduction of the JAR package

  2. Write the following code where you need to convert the JSON string

  • Convert a JSON string to an object
  1. The introduction of the JAR package

  2. Where you need to convert Java objects, write the following code:

Type object name = json.parseObject (JSON string, type.class);Copy the code

or

List< type > List = json.parsearray (JSON string, type.class);Copy the code

Case Demo:

public static void main(String[] args) {
    Book book = new Book("1002"."300 Tang Poems"."Moonlight by my bed.");
    Convert / / {" id ":" 1002 ", "info", "bed bright moonlight", "name" : "300 tang poems"}
    String json = JSON.toJSONString(book);
    System.out.println(json);

    // json to object
    Book book1 = JSON.parseObject("{"id":"1002","info":"Before my bed a pool of night","name":"The tang dynasty300The first"}", Book.class);
    System.out.println(book1.getName());
}
Copy the code

public static void main(String[] args) {
    // json to array [" one two three ", "two three four "," three four five "]
    List<String> strings = JSON.parseArray("["one two three","The 234","The 345"]", String.class);
    System.out.println(strings.get(2));
}
Copy the code

3 Jackson

  • Convert a JSON string to an object

Steps:

  1. Import the related JAR packages for Jackson

  1. Create the Jackson core object ObjectMapper

  2. Call the corresponding method of ObjectMapper for the transformation

ReadValue (JSON string data,Class)Copy the code

@Test
public void tes5(a) throws Exception {
    String json = "{"gender":"male","name":"Zhang SAN","age": 23}";

    ObjectMapper mapper = new ObjectMapper();
    Person person = mapper.readValue(json, Person.class);
    System.out.println(person);// toString() of the Person class
}
Copy the code

  • Java object conversion JSON
  1. Import the related JAR packages for Jackson

  2. Create the Jackson core object ObjectMapper

  3. Call the corresponding method of ObjectMapper for the transformation

WriteValue (parameter1Obj) :Copy the code

Parameter 1:

File: Converts an obj object to a JSON string and saves it to the specified File

Writer: Converts an OBj object to a JSON string and populates the JSON data into the character output stream

OutputStream: converts an obj object to a JSON string and populates the JSON data into a byte OutputStream

WriteValueAsString (obj): Converts an object to a JSON stringCopy the code

Person p = new Person();
p.setName("Zhang");
p.setAge(23);
p.setGender("Male");

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
System.out.println(json);

//writeValue, write data to d://a.txt file
mapper.writeValue(new File("d://a.txt"), p);

//writeValue to associate data with Writer
mapper.writeValue(new FileWriter("d://b.txt"),p);
Copy the code

Example: Verify whether the user name exists

The data that the server responds to, when used by the client, should be used as JSON data format. There are two solutions:

  1. $.get(type): specifies the last parameter type as “json”

  2. Set the MIME type on the server side

response.setContentType("application/json; charset=utf-8");
Copy the code

Front-end interface:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The sign-up page</title>
    <script src="Js/jquery - 3.3.1. Min. Js." "></script>
    <script>
        $(function () {$("#username").blur(function () {
                var username = $(this).val();
                // Send an Ajax request
                {"userExsit":true," MSG ":" This user name is too popular, please change it"}
                // {"userExsit":false," MSG ":" user name available "}
               $.get("findUserServlet", {username:username}, function (data) {
                   var span = $("#s_username");

                    if (data.userExsit){
                        span.css("color"."red");
                        span.html(data.msg);
                    }else {
                        span.css("color"."green"); span.html(data.msg); }},"json");
           });
        });
    </script>
</head>
<body>
    <form>

        <input type="text" id="username" name="username" placeholder="Please enter user name">
        <span id="s_username"></span>
        <br>
        <input type="password" name="password" placeholder="Please enter your password"><br>
        <input type="submit" value="Registered"><br>
    </form>
</body>
</html>
Copy the code

Corresponding servlets:

@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        1. Obtain the user name
        String username = request.getParameter("username");

        // 2. Invoke the service layer to check whether the user name exists
        // Set the data format of the response to JSON
        response.setContentType("application/json; charset=utf-8");

        Map<String , Object> map = new HashMap<>();
        if("tom".equals(username)){
            / / there
            map.put("userExsit".true);
            map.put("msg"."This username is too popular, please change it.");
        }else{
            / / does not exist
            map.put("userExsit".false);
            map.put("msg"."Username available");
        }

        // Convert the map to JSON and pass it to the client
        // Convert map to JSON
        ObjectMapper mapper = new ObjectMapper();
        // And passed to the client
        mapper.writeValue(response.getWriter(),map);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response); }}Copy the code

\