[英]Json Deserialize in multiple Java objects
我尝试反序列化 json:
{
"date": "2021_05",
"uuid": "3ba8b966-993f-49e0-b349-e528843a382c",
"dataset": "dataset",
"hmm_hit": "hit",
"hmm_evalue": "6.7e-186",
"hmm_score": "610.9"
},
我有两个实体:
@Entity
public class HmmResult {
@Id
@GeneratedValue
@JsonIgnore
private Integer id;
@JsonProperty("hmm_hit")
private String hmm;
@JsonProperty("hmm_evalue")
private String eValue;
@JsonProperty("hmm_score")
private Float score;
}
和
@Entity
public class Protein {
@Id
@GeneratedValue
@JsonIgnore
private Integer id;
@JsonProperty("date")
private String date;
@JsonProperty("uuid")
private String uuid;
@JsonProperty("dataset")
private String dataset;
@OneToOne
@JsonDeserialize(as = HmmResult.class)
private HmmResult hmmResult;
如何使用 json 的一个条目同时反序列化两个实体? 以下是 Jackson ObjectMapper 的主要摘录:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Protein p = objectMapper.readValue(new File(file), Protein.class);
它可以很好地解析“日期”、“uuid”和“数据集”,但无法解析带有“hmm_subfamily”、“hmm_evalue”和“hmm_score”值的 HmmResult object:我收到错误:p.getHmmResult(): null。 (HmmResult hm = objectMapper.readValue(new File(file), HmmResult.class); 单独工作也很好)。
对此有@JsonUnwrapped
注释。 应该像这样工作:
public class Protein {
@JsonProperty("date")
private String date;
@JsonProperty("uuid")
private String uuid;
@JsonProperty("dataset")
private String dataset;
@JsonUnwrapped
private HmmResult hmmResult;
}
var protein = new ObjectMapper().readValue(new File(file), Protein.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.