简体   繁体   English

Retrofit - 将 Json 响应映射反序列化为属性

[英]Retrofit - Deserilize Json response map into a property

I'm having a problem deserializing the response that I'm getting from retrofit.我在反序列化从改造中获得的响应时遇到问题。 My problem is that I get the following response:我的问题是我得到以下响应:

       "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"
            }
        }

My entity looks like the following:我的实体如下所示:

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;
    }
}

I want that association takes the value from the map, but I don't know how to specify that it takes the object inside that association.我希望该关联从地图中获取值,但我不知道如何指定它获取该关联中的对象。 Those association keys can be returned as any number, so I can't hard code the "1".这些关联键可以作为任何数字返回,所以我不能硬编码“1”。 Any ideas?有任何想法吗? Thanks for your help!谢谢你的帮助!

You can read your json to a JsonNode and iterate over its properties names with a Iterator<String> iterator obtained calling the JsonNode#fieldNames method, selecting only the properties with a numeric name (this depends from what you mean for numeric, up to you the definition of a isNumber method):您可以将 json 读取到JsonNode并使用调用JsonNode#fieldNames方法获得的Iterator<String>迭代器迭代其属性名称,仅选择具有数字名称的属性(这取决于您对数字的含义,取决于您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));
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM