Simple use of JSON

Keywords: Java JSON data structure


1, What is JSON?

The full name of JSON is JavaScript object notation. JavaScript object notation is a data structure that replaces XML. Now JSON is mostly used to store and exchange the syntax of text information for data transmission. JSON is smaller, faster and easier to parse than XML. Moreover, the JSON parser and JSON library support many different programming languages.

2, Syntax:

Basic rules

Data in name / value pairs: json data consists of key value pairs

  • Keys and values can be enclosed in quotation marks (either single or double), or keys can be enclosed without quotation marks

  • Value type:

    1. Number (integer or floating point number)
    2. String (in double quotes)
    3. Logical value (true or false)
    4. Array (in square brackets) {"persons": [{}, {}]}
    5. Object (in curly braces) {"address": {"province": "Heilongjiang"...}}
    6. null
  • Data is separated by commas: multiple key value pairs are separated by commas

  • Curly brace save object: use {} to define json format

  • Square bracket save array: []

  • : a colon indicates that the latter is the value of the former (this value can be a string, a number, or another array or object)

For example:

		"IDayCn":"ninth day of a lunar month",
      "five":["Water and fire","Water water","Wood","Golden fire"],

result represents a json object, where year and month are its attributes, and five represents an array in which json objects can be nested.

3, How to parse JSON

JSON parser:
Common parsers: Jsonlib, Gson, fastjson and jackson. Only Gson and fastjson are introduced here.

1. Use Gson parsing

First, introduce the dependency of Gsonjar package


JSON object to Java object

Directly create a Gson object and call the toJson method of its object to parse a Java object into a JSON object

        Gson gson = new Gson();
        Book book = new Book();
        book.setName("Brief history of time");
        book.setInfo("Quantum physics");
        //Object conversion json
        String json = gson.toJson(book);
        System.out.println(json );

Output as

{"id":"100","name":"Brief history of time","info":"Quantum physics"}

Turn JSON into a Java object and call its fromJson method

        //json conversion object
        String json = "{\"id\":\"100\",\"name\":\"Brief history of time\",\"info\":\"Quantum physics\"}";
        Book book1 = gson.fromJson(json, Book.class);

Output as

Book{id='100', name='Brief history of time', info='Quantum physics'}

You can also convert JSON to HashMap type

String json = "{\"id\":\"100\",\"name\":\"Brief history of time\",\"info\":\"Quantum physics\"}";
HashMap hashMap = gson.fromJson(json, HashMap.class);

Output as

{name=Brief history of time, id=100, info=Quantum physics}

If there is an array type in a JSON object, Gson will automatically convert it to an ArrayList array

For example, the previous example

        String s = "{\"five\":[\"Water and fire\",\"Water water\",\"Wood\",\"Golden fire\"],\"lose\":\"Soil\"}";
        HashMap hashMap = gson.fromJson(s, HashMap.class);

Output as

{lose=Soil, five=[Water and fire, Water water, Wood, Golden fire]}

2. Use fastjson to parse

First, introduce dependencies


Convert a Java object into a JSON object, and directly call the static method toJSONString() of the JSON object to pass in the Java object to be converted

        Book book = new Book();
        book.setName("The Great Gatsby");
        book.setInfo("A tragic love story");
        //Object to json
        String s = JSON.toJSONString(book);

Output is:

{"id":"10086","info":"A tragic love story","name":"The Great Gatsby"}

Similarly, it is the same for converting JSON objects to Java, calling its parse method or parseObject method

        //json to object
        Book object = JSON.parseObject("{\"id\":\"10086\",\"info\":\"A tragic love story\",\"name\":\"The Great Gatsby\"}", Book.class);
        Object parse = JSON.parse("[ \"Porsche\", \"BMW\", \"Volvo\" ]");


Book{id='10086', name='The Great Gatsby', info='A tragic love story'}

The second parameter of the parseObject method can pass in different types of class objects to get the desired type

        HashMap hashMap = JSON.parseObject("{\"id\":\"10086\",\"info\":\"A tragic love story\",\"name\":\"The Great Gatsby\"}", HashMap.class);


{name=The Great Gatsby, id=10086, info=A tragic love story}

There are many API s for the conversion between JSON and Java objects, and only simple usage is introduced here.

Posted by webbwbb on Sun, 24 Oct 2021 13:09:02 -0700