Problems encountered in converting java objects to json format and then converting json to java objects

Problems encountered in converting java objects to json format and then converting json to java objects

`````

1. Under normal circumstances

1. The first class

package com.zevin;

import com.fasterxml.jackson.annotation.JsonProperty;

public class User1 {
    
    
    @JsonProperty("user_name")//把属性的名称序列化时转换为另外一个名称,即userName->user_name
    private String userName;//采用驼峰命名原则

    public String getUserName() {
    
    
        return userName;
    }

    public void setUserName(String userName) {
    
    
        this.userName = userName;
    }
}

2. The second class

package com.zevin;

public class User2 {
    
    
    private String user_name;//数据库命名规则

    public String getUser_name() {
    
    
        return user_name;
    }

    public void setUser_name(String user_name) {
    
    
        this.user_name = user_name;
    }
}

3. Test class

    @Test
    public void test01() throws JsonProcessingException {
    
    
        //创建javaObject
        User1 user1 = new User1();
        user1.setUserName("zevin");
        System.out.println("javaObject.userName:"+user1.getUserName()+"\n");

        //创建基于"对象绑定"解析的相关API,即ObjectMapper(内置一对ObjectWriter和ObjectReader)
        ObjectMapper mapper = new ObjectMapper();

        //javaObject->JsonString,即调用ObjectWriter进行序列化
        String JsonStringByUser1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user1);
        System.out.println("将javaObject序列化成json格式字符串:\n"+JsonStringByUser1+"\n");

        //JsonString->javaObject,即调用ObjectReader进行反序列化
        User2 user2 = mapper.readValue(JsonStringByUser1, User2.class);
        System.out.println("将json格式字符串反序列化成javaObject:\njavaObject.user_name:"+user2.getUser_name()+"\n");
    }

4. The print result is normal

1.javaObject.userName:zevin
2. Serialize javaObject into json format string:
{ “user_name” : “zevin” } 3. Deserialize json format string into javaObject: javaObject.user_name:zevin



`````

2. With the parameterized construction method, an exception occurs

1. Others remain unchanged, modify the second class

public class User2 {
    
    
    private String user_name;//数据库命名规则

    public User2(String user_name) {
    
    
        this.user_name = user_name;
    }

    public String getUser_name() {
    
    
        return user_name;
    }

    public void setUser_name(String user_name) {
    
    
        this.user_name = user_name;
    }
}

2. Print the result and display an exception during the deserialization process

  1. javaObject.userName:zevin
    2.将javaObject序列化成json格式字符串:
    {
    “user_name” : “zevin”
    }
    3.com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.zevin.User2 (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
    at [Source: (String)“{
    “user_name” : “zevin”
    }”; line: 2, column: 3]

3. Solution: remove the parameterized structure, or add a parameterless structure

`````

3. The attribute names of the java object and json are inconsistent, and an exception occurs

1. Others remain unchanged, modify the second class

package com.zevin;

public class User2 {
    
    
    private String userName;//跟第一类属性名保持一致

    public String getUserName() {
    
    
        return userName;
    }

    public void setUserName(String userName) {
    
    
        this.userName = userName;
    }
}

2. Print the result and display an exception during the deserialization process

1.javaObject.userName:zevin
2.将javaObject序列化成json格式字符串:
{
“user_name” : “zevin”
}
3.com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “user_name” (class com.zevin.User2), not marked as ignorable (one known property: “userName”])
at [Source: (String)“{
“user_name” : “zevin”
}”; line: 2, column: 18] (through reference chain: com.zevin.User2[“user_name”])

3. Solution: Change the setUserName method to setUser_name(), or add @JsonProperty("user_name") to be consistent with the first class

`````

4. Delete the setter method, an exception occurs

1. Others remain unchanged, modify the second class

package com.zevin;

public class User2 {
    
    
    private String user_name;//json属性名保持一致

    public String getUser_name() {
    
    
        return user_name;
    }

    //public void setUserName(String userName) {
    
    
    //    this.userName = userName;
    //}
}

2. Print the result and display an exception during the deserialization process

javaObject.userName:zevin
将javaObject序列化成json格式字符串:
{
“user_name” : “zevin”
}
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “user_name” (class com.zevin.User2), not marked as ignorable (0 known properties: ])
at [Source: (String)“{
“user_name” : “zevin”
}”; line: 2, column: 18] (through reference chain: com.zevin.User2[“user_name”])

3. Solution: add a setter method, the method name must be setUser_name(), or add @JsonProperty("user_name")

`````

5. Use @JsonProperty and sertter methods at the same time, but they are inconsistent

1. Others remain unchanged, modify the second class

package com.zevin;

import com.fasterxml.jackson.annotation.JsonProperty;

public class User2 {
    
    
	@JsonProperty("user_name")
    private String userName;//跟第一类属性名保持一致

    public String getUserName() {
    
    
        return userName;
    }

    public void setUserName(String userName) {
    
    
        this.userName = userName;
    }
}

2. The print result shows normal, then test the following cases, and continue to modify the second class

package com.zevin;

import com.fasterxml.jackson.annotation.JsonProperty;

public class User2 {
    
    
    @JsonProperty("userName")
    private String userName;//跟第一类属性名保持一致

    public String getUserName() {
    
    
        return userName;
    }

    public void setUser_name(String userName) {
    
    
        this.userName = userName;
    }
}

3. The print result is still normal

`````

in conclusion

1. Java objects can be generated normally as long as they meet any of the following conditions:

1. The value of @JsonProperty on the object property is the same as the json property name

2. The method name of the setter method of the object property is the same as the json property name

That is, the @JsonProperty("prop") or setProp() in the java object is consistent with the prop value of {"prop":"value"} in the json

2. In special circumstances, it cannot be generated

1. Use the java object of the first class to generate jsonString

public class User1 {
    
    
    @JsonProperty("user_name")
    private String userName;

    public String getUserName() {
    
    
        return userName;
    }

    public void setUserName(String userName) {
    
    
        this.userName = userName;
    }
}

2. Use jsonString to generate the java object of the second class, even if the attribute names are the same, an error will be reported

public class User2 {
    
    
    private String user_name;

    public String getUserName() {
    
    
        return user_name;
    }
    //没有@JsonProperty和setter方法
}

3. Jackson's "object binding"-based API is related to the setter method and the use of @JsonProperty. If you don't know clearly, you need to look at the source code

Guess you like

Origin blog.csdn.net/m0_61849361/article/details/124664854
Recommended