jackson Retrofit -将Json响应Map反序列化为属性

6vl6ewon  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(100)

我在反序列化我从retrofit中获得的响应时遇到问题。我的问题是我得到了以下响应:

"associations": {
            "1": {
                "uri": "https://api.ap.org/media/v/content/690b9f679b1d4d8abc8042ca53140625?qt=FckGhfkHkvF&et=0a1aza3c0&ai=881778bb579d79e17f54b046a86a81cf",
                "altids": {
                    "itemid": "690b9f679b1d4d8abc8042ca53140625",
                    "etag": "690b9f679b1d4d8abc8042ca53140625_0a1aza3c0"
                },
                "version": 0,
                "type": "picture",
                "headline": "Facebook Ads-Targeting Info"
            }
        }

我的实体如下所示:

public class Associations{

    private Map<String, JsonMember> association;

    public Map<String, JsonMember> getAssociation() {
        return association;
    }

    public void setAssociation(Map<String, JsonMember> association) {
        this.association = association;
    }
}

我想让关联从Map中获取值,但我不知道如何指定它获取关联中的对象。那些关联键可以作为任何数字返回,所以我不能硬编码“1”。有什么想法吗?谢谢你的帮助!

xqnpmsa8

xqnpmsa81#

你可以把json读到JsonNode,然后用Iterator<String>迭代器迭代它的属性名,这个迭代器是通过调用JsonNode#fieldNames方法获得的,只选择带有 numeric 名称的属性(这取决于你对numeric的意思,取决于你对isNumber方法的定义):

Map<String, JsonMember> map = new HashMap<>();
//reading the jsonnode labelled with "associations"
JsonNode node = mapper.readTree(json).at("/associations");
Iterator<String> iterator = node.fieldNames();
        
while (iterator.hasNext()) {
      String next = iterator.next();
      if (isNumber(next)) { //<-- ok next is numeric
         map.put(next, mapper.treeToValue(node.get(next), JsonMember.class));
      }
}

相关问题