使用不同的对象名称映射 JSON [英] Mapping JSON with varying object name

查看:27
本文介绍了使用不同的对象名称映射 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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;

和映射使用:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆