JSON parsing--java practical orientation--On the basics of JSON, it is enough to read this article

Table of contents

1. What is JSON ( ̄︶ ̄)↗

all in all:

2. Why use JSON

Three, different JSON parsing methods

        3.1 gson and fastjson

        in short

        3.2 gson case

        3.2.1 Use gson, bean to json

                Case 1: toJson()

                Case 2: toJson() anonymous creation method

        3.2.2 Parsing json content with gson

                Case 1: fromJson() - parsed json content, (when it is an object)

                Case 2: fromJson() - when the parsed json content contains an array

                in conclusion

                Given conclusion 2

     3.3 fastjson case

3.3.1 Case 1: toJS3ONString() - convert object to json format

3.3.2 Case 2: patseObject() 

3.3.3 Case 3: When the converted object contains an array

result:

4. Attachments ~(~ ̄▽ ̄)~

4.1 gson's official guidance documents and excellent translations

4.2 Address of gson 

4.3 The address of json 

5. Message from the author


1. What is JSON ( ̄︶ ̄)↗

1. JSON ( JavaScript  Object Notation, JS Object Notation) is a lightweight data exchange format .

2. It is based on   a subset of ECMAScript (the js specification developed by the European Computer Association), and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clear hierarchy make JSON an ideal data interchange language .

all in all:

 JSON is a language format for front-end and back-end communication, which enables content in different languages ​​to be mutually converted and understood. 

 And it is also the main data format for front-end and back-end transmission in the future development. 

benefit: 

        It is easy for people to read and write , and it is also easy for machines to parse and generate , and it can effectively improve the efficiency of network transmission .

2. Why use JSON

There are 4 reasons:

  1. Save space, there are basically no wasted characters, so the transmission rate is faster. Although JSON is similar to XML, it is smaller, faster, and easier to parse than XML.

  2. JSON syntax is simple, easy to understand, and most companies use JSON.

  3. It has nothing to do with the language, the support is very impressive, and any language can easily use it for format conversion.

  4. Type safety, the value is typed, such as integer, string, Boolean, etc.

Three, different JSON parsing methods

        3.1 gson and fastjson

               3.1.1 What is gson

        Gson (also known as Google Gson) is an open source Java library released by Google. Its main purpose is to serialize Java objects into JSON strings, or deserialize JSON strings into Java objects.

        in short

        It is a tool developed by Google that can convert java objects into json format, and then convert json format into java objects.

               3.1.2 What is fastjson

 FastJson is Alibaba's open source library for parsing and packaging data in JSON format.

               3.1.3 Differences and Features

  1. Gson has comprehensive functions , but there is a gap in performance compared to fastjson
  2. FastJson uses an original algorithm to increase the speed of parse to the extreme , surpassing all json libraries, but it is prone to some problems in the conversion of complex types, and the type of reference may appear, resulting in errors in Json conversion, and it is necessary to formulate references.

               3.1.4 Applicable scenarios

  1. If there are only functional requirements and no performance requirements, you can use Google's Gson ,
  2. If there are performance requirements above, you can use Gson to convert beans to json to ensure the correctness of the data, and use FastJson to convert Json to beans

           3.2 gson case

Note: In all the following cases, you need to create a BOOK class first

The properties are:

                

The methods are:

  1.         All get(), set() methods
  2.         hashCode(), equals() method
  3.         full parameter constructor
  4.         toString() method

3.2.1 Use gson, bean to json

Case 1:  toJson()

 //谷歌的方式
        //1.    创建一个Gson对象
        Gson g = new Gson();
        //2.    转换
        Book b = new Book("99","牛顿的苹果","牛顿在树下被苹果砸到");
        String s = g.toJson(b);
        System.out.println(s);

  result 

 {"id":"99","name":"Newton's apple","info":"Newton was hit by an apple under the tree"}

 Case 2:    toJson() anonymous creation method

//1.    创建一个Gson对象
        //2.    转换
        Book b = new Book("99","牛顿的苹果","牛顿在树下被苹果砸到");
        String s =new Gson().toJson(b);
        System.out.println(s);

 result:

{"id":"99","name":"Newton's apple","info":"Newton was hit by an apple under the tree"}

3.2.2 Parsing json content with gson

Case 1: fromJson()   - parsed json content, (when it is an object)

//1.    创建一个Gson对象
        Gson g = new Gson();
        //2.    转换json后输出  ,第一个参数传的是json字符串   ,第二个参数是要转换成什么样的类型
        Book b = g.fromJson("{\"id\":\"99\",\"name\":\"牛顿的苹果\",\"info\":\"牛顿在树下被苹果砸到\"}",Book.class);
        System.out.println(b.getId());


//匿名对象
//1.    创建一个Gson对象
        //2.    转换json后输出  ,第一个参数传的是json字符串   ,第二个参数是要转换成什么样的类型
        Book b2 = new Gson().fromJson("{\"id\":\"99\",\"name\":\"我的世界观\",\"info\":\"爱因斯坦著作集\"}",Book.class);
        System.out.println(b2.getId());

 Case 2: fromJson() - when the parsed json content contains an array

 //1.    创建一个Gson对象
        //2.    转换输出  {"id":"99","name":"牛顿的苹果","info":"牛顿在树下被苹果砸到","page":["锄禾日当午","汗滴禾下土","嘿嘿嘿"]}  ,第一个参数传的是json字符串   ,第二个参数是要转换成什么样的类型
        HashMap data = new Gson().fromJson("{\"id\":\"99\",\"name\":\"牛顿的苹果\",\"info\":\"牛顿在树下被苹果砸到\",\"page\":[\"锄禾日当午\",\"汗滴禾下土\",\"嘿嘿嘿\"]}", HashMap.class);
        System.out.println(data.get("page").getClass());
        //.getClass()获取类型,得到的类型是ArrayList。

in conclusion

1. Normal cases, anonymous cases, and objects containing arrays are also output according to the format in toString or subscripts

2. However, when the converted object contains an array part, the array content will be automatically converted into a List collection 

       Given conclusion 2

We can directly convert the array into a List collection for output

 //1.    创建一个Gson对象
        //2.    转换json后输出  {"id":"99","name":"牛顿的苹果","info":"牛顿在树下被苹果砸到","page":["锄禾日当午","汗滴禾下土","嘿嘿嘿"]}  ,第一个参数传的是json字符串   ,第二个参数是要转换成什么样的类型
        HashMap data = new Gson().fromJson("{\"id\":\"99\",\"name\":\"牛顿的苹果\",\"info\":\"牛顿在树下被苹果砸到\",\"page\":[\"锄禾日当午\",\"汗滴禾下土\",\"嘿嘿嘿\"]}", HashMap.class);
        List page = (List) data.get("page");
        System.out.println(page.get(1));

     3.3 fastjson case

3.3.1 Case 1: toJSONString()   - convert the object into json format

Book b = new Book("66","唐诗三百首","床前明月光");
        //1. 转换
        String json = JSON.toJSONString(b);
        System.out.println(json);

Since the output result is similar to the above, the result will not be released.

3.3.2 Case 2: patseObject() 

//1. 转换  {"id":"66","info":"床前明月光","name":"唐诗三百首"}
        Book b = JSON.parseObject("{\"id\":\"1002\",\"info\":\"床前明月光\",\"name\":\"唐诗三百首\"}",Book.class);
        System.out.println(b);

3.3.3 Case 3: When the converted object contains an array

Notice: 

        Here, Ali's fastjson is different from Google's gson:

         fastjson needs to use the parseArray() method, but gson has not changed

 parseArray():

/1. 转换  :["一二三四五","幸福生活奋斗来","三四五"]
        List<String> s = JSON.parseArray("[\"一二三四五\",\"幸福生活奋斗来\",\"三四五\"]",String.class);
        //List<String> List集合里面是字符串
        //结果是一个List集合
        //打印一下1下标
        System.out.println(s.get(1));

result:

happy life struggle

4. Attachments ~(~ ̄▽ ̄)~

4.1 gson's official guidance documents and excellent translations

Official documentation:

gson/UserGuide.md at master · google/gson · GitHub

Excellent translation:

http://www.javacreed.com/

4.2 Address of gson 

Gitee fast download/gson

4.3 The address of json 

Releases · alibaba/fastjson · GitHub

5. Message from the author

1. If this article is helpful to you, how about like, repost, bookmark? It would be better if there is attention. 0.0. Thank you so much~

 2. Finally, if there are any mistakes or deficiencies in this article, if you can point it out, the author will definitely listen to it with an open mind~ Make corrections carefully, thank you~

Guess you like

Origin blog.csdn.net/weixin_53353693/article/details/120079042