Json parsing format

1. What is Json

JSON is a substituted XML data structure, and compared to xml, but it is more compact and does not describe differential ability, because of its small so reducing the network traffic so that more traffic speed.

JSON is just a bunch of string elements will use specific signs while.

Bis {} brackets indicate the object
[] array in brackets indicate
"" is in quotation marks or attribute value
: represents the colon which is the former value (this value may be a string, a number, or may be another array or object)

Therefore, { "name": "Michael"} may be understood as a name for the object containing the Michael

2.Json four ways to resolve

2.1 traditional way json-lib

Import dependence:

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

Entity class into json string
entity classes:

public class User {
    private Integer age;
    private String name;
    private String password;

    public User() {}

    public User(Integer age, String name, String password) {
        this.age = age;
        this.name = name;
        this.password = password;
    }
}

Json Test categories:

public class JsonTest {

    /**
     * 传统方式解析:实体类转换为Json格式字符串
     */
    private static void tranBeanToJson() {
        User user = new User(18, "zzc", "666");
        JSONObject json = new JSONObject();

        json.put("age", user.getAge());
        json.put("name", user.getName());
        json.put("password", user.getPassword());

        System.out.println(json.toString());
    }

    /**
     * 传统方式解析
     */
    public static void tranditioalResolve() {
        tranBeanToJson();
    }


    public static void main(String[] args) {
        tranditioalResolve();
    }
}

Here Insert Picture Description
Json string into a format entity class

/**
* 传统方式解析:Json格式字符串转换为实体类
 */
private static void tranJsonToBean() {
    String jsonStr = "{\"age\" :20, \"name\": \"zzc\", \"password\": \"123\"}";
    JSONObject json = JSONObject.fromObject(jsonStr);
    User user = (User) json.toBean(json, User.class);
    System.out.println(user);
}

public static void tranditioalResolve() {
   //tranBeanToJson();
    tranJsonToBean();
}

Here Insert Picture Description
If the string contains an array Json

Add the Address class:

public class Address {
    private String province;
    private String city;
    private String block;
    private Integer street;

    public Address() {}

    public Address(String province, String city, String block, Integer street) {
        this.province = province;
        this.city = city;
        this.block = block;
        this.street = street;
    }
}

And the class as a property of Address User class. Modify User class:

public class User {
    private Integer age;
    private String name;
    private String password;
    // 一个用户可以有多个地址
    private List<Address> addressList;
}
private static void tranJsonToBean() {

    String jsonStr = "{\"age\":20, \"name\":\"zzc\", \"password\":\"123\", \"addressList\":" +
            "[{\"province\": \"湖北省\", \"city\":\"武汉市\", \"block\":\"东西湖区\", \"street\": \"556\"}," +
            "{\"province\": \"黑龙江省\", \"city\":\"哈尔滨市\", \"block\":\"道里区\", \"street\": \"36\"}]}";
    
    JSONObject json = JSONObject.fromObject(jsonStr);
    Map classMap = new HashMap<>();
    classMap.put("addressList", Address.class);
    User user = (User) json.toBean(json, User.class, classMap);
    System.out.println(user);
}

AddressList above is an array. In this case, the need for assembling a Map. In this way, addressList property User object was assigned a.

Also be obtained by the method addressList value getJSONArray () Method:

JSONArray addressList = json.getJSONArray("addressList");
System.out.println(addressList);

2.2Jackson way

Import dependence:

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

Entity class into a format Json

private static void jacksonBeanToJson() throws Exception{
    User user = new User(18, "zzc", "666");

    ObjectMapper objectMapper = new ObjectMapper();
    String jsonStr = objectMapper.writeValueAsString(user);
    System.out.println(jsonStr);
}

public static void jacksonResolve() {
    try {
        jacksonBeanToJson();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    jacksonResolve();
}

Json string into a format entity class

private static void jacksonJsonToBean() throws Exception{
    String jsonStr = "{\"age\" :20, \"name\": \"zzc\", \"password\": \"123\"}";

    ObjectMapper objectMapper = new ObjectMapper();
    User user = objectMapper.readValue(jsonStr, User.class);
    System.out.println(user);
}

2.3Gson resolve

Import dependence:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

Entity class into a format Json

private static void gsonBeanToJson() {
    User user = new User(18, "zzc", "666");

    Gson gson = new Gson();
    String jsonStr = gson.toJson(user);
    System.out.println(jsonStr);
}

Json string into a format entity class

private static void gsonJsonToBean() {
    String jsonStr = "{\"age\" :20, \"name\": \"zzc\", \"password\": \"123\"}";

    Gson gson = new Gson();
    User user = gson.fromJson(jsonStr, User.class);
    System.out.println(user);
}

2.4fastjson resolve

Import dependence:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

Entity class into a format Json

private static void fastJsonBeanToJson() {
    User user = new User(18, "zzc", "666");

    Object jsonStr = JSON.toJSON(user);
    System.out.println(jsonStr);
}

Json string into a format entity class

private static void fastJsonToBean() {
    String jsonStr = "{\"age\" :20, \"name\": \"zzc\", \"password\": \"123\"}";

    User user = JSON.parseObject(jsonStr, User.class);
    System.out.println(user);
}

3. Comparison of four kinds of analytical methods

Way to resolve differences

3.1json-lib

        json-lib the beginning, is the most widely used analytical tool json, json-lib a bad place really is dependent on many third-party packages (including commons-beanutils.jar, commons-collections-3.2.jar, commons-lang- 2.6.jar, commons-logging-1.1.1.jar, ezmorph-1.0.6.jar) for complex type of conversion, json-lib converted to json bean there defects, such as occur inside a class of another class list or map set, json-lib problem arises from bean to json conversion.

        json-lib in function and performance of the above can not meet the needs of the Internet now.

3.2 open source Jackson

        Compared json-lib frame, Jackson jar package depends less easy to use and the performance should be relatively higher. And Jackson community is relatively active, the speed is faster.

        Jackson bean cause problems for complex json type of conversion, a collection of Map, List of the conversion problems. Jackson For complex types of bean convert Json, convert Json json format instead of the standard format

3.3Google 的 Gson

        Gson is the most versatile Json parsing application artifacts .Gson mainly toJson and fromJson two conversion functions, no dependence, no exceptions extra jar, can be directly run on JDK. As long as the class which get and set methods, can Gson complex type or bean to bean to json json conversion is JSON parsing artifact.

        Gson in the above function impeccable, but the performance gap somewhat above than FastJson.

3.4 Alibaba FastJson

        Fastjson Java language is written in a high-performance JSON processor, developed by Alibaba. No dependence, no additional jar exception, can be directly run on JDK.
FastJson will appear on a complex type of Bean convert Json some of the problems, the type of reference may occur, resulting Json conversion error, the need for reference.

        FastJson using original algorithm, will parse the speed to the extreme, more than all the json library.

Analytical type Advantages and disadvantages
json-lib Json data into a complex entity class defects, inadequate performance and functionality
Jackson Json data into a complex entity class flawed, the performance and functionality than conventional manner
Gson Function in several ways optimal performance as good as the way Jackson
Fast Json Defective complex entity class Json converted into data, parsing speed than otherwise json
Published 78 original articles · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/Lucky_Boy_Luck/article/details/104732861