我遇到反序列化问题:

这是我的课:

public class Response {

    private Object ResObj;
    private int ResInt;

    public Object getResObj() {
        return ResObj;
    }

    public int getResInt() {
        return ResInt;
    }
}

我要反序列化的JSON是:
{"ResObj":{"ClientNum":"12345","ServerNum":"78945","IdNum":"020252"},"ResInt":0}

我得到这个异常:
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"])

我不想添加:
@JsonIgnoreProperties(ignoreUnknown = true)

因为我想得到ResObj ...

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

最佳答案

如果您不想在bean中使用 setter ,而只使用字段和 getter ,则可以使用ObjectMapper的可见性检查器来允许字段可见。
如下所示:

ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));

10-06 06:17