使用不同的对象名称映射JSON [英] Mapping JSON with varying object name
问题描述
我对JSON很陌生,我已经四处寻找尝试做什么但不确定我是否完全理解。我正在进行外部API调用返回:
I'm quite new to JSON, and I've looked around trying to work out what to do but not sure if I fully understand. I am making an external API call returning:
2015-12-21 01:22:09 INFO RiotURLSender:60 - Total json:
{"USERNAME":{"profileIconId":984,"revisionDate":1450655430000,"name":"USERNAME2","id":38584682,"summonerLevel":30}}
其中'USERNAME'(和USERNAME2 - 可能与USERNAME略有不同)将根据您传递调用参数的内容而有所不同。我使用Jackson Object Mapper来映射USERNAME对象中的各个值 - 但是没有意识到我也必须映射该对象。
Where 'USERNAME' (And USERNAME2 - which can be very slightly different to USERNAME) will vary depending on what you pass the call's parameters. I was using Jackson Object Mapper to map the individual values within the USERNAME object - but didn't realise I had to map the object as well.
我一直在使用DTO中的注释如:
I've been using annotations in the DTOs like:
@JsonProperty("profileIconId")
private Long profileIconId;
并使用以下方式进行映射:
and mapping using:
summonerRankedInfoDTO = mapper.readValue(jsonString, SummonerRankedInfoDTO.class);
如何使用每次更改的USERNAME值进行映射?
How do I map using a value of USERNAME which is changing every single time?
另外这看起来有点奇怪,这种不好的做法是不是只拥有相同的密钥和不同的值?
Also this seems a bit odd, is this bad practice to have the actual varying key rather than just have the same key and different value?
谢谢
推荐答案
您可以使用以下提到的注释@JsonAnyGetter和@JsonAnySetter。
将此代码添加到您的域类中。因此,在对序列化和反序列化对象时,任何非映射属性都将填充到nonMappedAttributes映射中。
you can use following mentioned annotation @JsonAnyGetter And @JsonAnySetter. Add this code into ur domain class. So any non-mapped attribute will get populated into "nonMappedAttributes" map while serializing and deserializing the Object.
@JsonIgnore
protected Map<String, Object> nonMappedAttributes;
@JsonAnyGetter
public Map<String, Object> getNonMappedAttributes() {
return nonMappedAttributes;
}
@JsonAnySetter
public void setNonMappedAttributes(String key, Object value) {
if (nonMappedAttributes == null) {
nonMappedAttributes = new HashMap<String, Object>();
}
if (key != null) {
if (value != null) {
nonMappedAttributes.put(key, value);
} else {
nonMappedAttributes.remove(key);
}
}
}
这篇关于使用不同的对象名称映射JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!