Mapping JSON with varying object name

前端 未结 2 1599
余生分开走
余生分开走 2020-12-11 11:22

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:



        
相关标签:
2条回答
  • 2020-12-11 11:33

    You should try to keep the keys the exact same if possible and change values, otherwise you'll have to change your JSON. Since JSON returns a value from the key, the value can change to anything it wants, but you'll be able to return it from the key. This doesn't work the other way around though.

    Anyway to your question, you may have a little better luck using something like the GSON library, its pretty simple to use.

    You can create the instance and pass it the JSON string:

    Gson gson = new Gson();
    JsonObject obj = gson.fromJson(JSON_DOCUMENT, JsonObject.class);
    

    Then you can get certain elements from that now parsed JSON object.

    For example, in your JSON string, username returns another JSON element, so you can do:

    JsonObject username = obj.get("USERNAME").getAsJsonObject();
    

    Then just repeat the same steps from there to get whatever value you need. So to get the name which returns "USERNAME2":

    username.get("name").getAsString();
    

    Coming together with:

    JsonObject obj = gson.fromJson(JSON_DOCUMENT, JsonObject.class);
    JsonObject username = obj.get("USERNAME").getAsJsonObject();
    username.get("name").getAsString();
    
    0 讨论(0)
  • 2020-12-11 11:42

    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);
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题