我试图为此寻找答案,但意识到有多个相似之处,但没有一个与此相符。
我有一个具有这种结构的JSON对象
{
"model": {
"serie" : "123456",
"id" : "abc123"
/// many fields
},
"externalModel": {
"serie" : "123456",
"fieldX" : "abcde"
// many fields as well
}
我正在用我的代码执行此操作:
ObjectMapper mapper = new ObjectMapper();
MyObject object = mapper.readValue(hit.getSourceAsString(), MyObject.class);
其中MyObject具有以下形式:
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {
@JsonProperty("serie")
String serie;
@JsonProperty("id")
Long id;
MyObject() {}
}
当我进行转换时,我没有任何异常,但是我得到的myObject的所有值都设置为 null
我不知道有什么问题,因为没有异常返回,知道吗?
答案 0 :(得分:2)
您需要使用根属性model
,
您可以将MyObject
重命名为MyModel
并创建一个MyObject
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject{
@JsonProperty("model")
MyModel model;
}
然后检查model
答案 1 :(得分:1)
实际上,您在MyObject中需要两个对象。
mysql
现在,当您像下面那样使用它时,它将可以正常工作。
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyModel {
@JsonProperty("id")
private String id;
@JsonProperty("serie")
private String serie;
//Generate getters and setters of these two
}
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExternalObject {
@JsonProperty("serie")
private String serie;
@JsonProperty("fieldX")
private String fieldX;
//Generate getters and setters of these two
}
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject{
@JsonProperty("model")
private MyModel model;
@JsonProperty("externalModel")
private ExternalObject externalModel;
//Generate getters and setters of these two
}