com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段

use*_*726 18 java json jackson

我有一个反序列化问题:

这是我的班级:

public class Response {

    private Object ResObj;
    private int ResInt;

    public Object getResObj() {
        return ResObj;
    }

    public int getResInt() {
        return ResInt;
    } 
} 
Run Code Online (Sandbox Code Playgroud)

我想要反序列化的JSON是:

{"ResObj":{"ClientNum":"12345","ServerNum":"78945","IdNum":"020252"},"ResInt":0}
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ResObj" , not marked as ignorable (0 known properties: ])
 at [Source: java.io.StringReader@1f758500; line: 1, column: 20] (through reference chain: ["ResObj"])
Run Code Online (Sandbox Code Playgroud)

我不想补充:

@JsonIgnoreProperties(ignoreUnknown = true)
Run Code Online (Sandbox Code Playgroud)

因为我想得到ResObj ...

如果我添加注释,它会通过,但它会将其设置为null ..这是我不想要的.

Jay*_*Jay 43

如果您不想在bean中使用setter并且只使用字段和getter,则可以使用ObjectMapper的可见性检查器来允许字段可见性.跟随之类的事情

ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setVisibilityChecker(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
Run Code Online (Sandbox Code Playgroud)


jon*_*son 8

您需要Setter方法来允许Jackson设置属性,您需要更改json中的字段以小写字母开头:

public class Response {

    private Object ResObj;
    private int ResInt;

    public Object getResObj() {
        return ResObj;
    }

    public void setResObj(Object ResObj) {
        this.ResObj = ResObj;
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

和:

{"resObj":{"clientNum":"12345","serverNum":"78945","idNum":"020252"},"resInt":0}
Run Code Online (Sandbox Code Playgroud)

JSON更改的原因是Jackson bean序列化将反映在类上,当它看到getXyz()和setXyz()时,方法会将这些映射到Json字段名称"xyz"(而不是"Xyz").

我认为有几种方法可以覆盖这种行为,一种是使用杰克逊注释之一.


Ash*_*ish 5

我想你应该试试看

public class Response {
    @JsonProperty
    private Object ResObj;
    @JsonProperty
    private int ResInt;

    public Object getResObj() {
        return ResObj;
    }

    public int getResInt() {
        return ResInt;
    } 
} 
Run Code Online (Sandbox Code Playgroud)

它将通过UnrecognizedPropertyExceptions解决您的问题