3

There's a library class, the definition is:

class LibraryBean {
    public String tag;
    public Map<String, Object> attributes;
}

In my application code, I know every possible key for the attributes map, and the type of value of a certain key is fixed, for example, if the key is "location" then the value type is Location, if the key is "timestamp" then the value type is Long. Writing an ArrayList<LibraryBean> to a json string is simple, but how can I deserialize the json string so that the value recovers its type?

public void test(ArrayList<LibraryBean> sampleList) { 
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeAsString(sampleList);

        List<LibraryBean> recovered = mapper.readValue(jsonString); // what should I do here?

        // I'm sure sampleList.get(0).attributes.get("location") != null
        AssertTrue(sampleList.get(0).attributes.get("location") instanceof Location);
    }
1
  • It is not a good idea to have a map with different value types. Think about creating a map per type to avoid casting. Commented Nov 11, 2015 at 6:51

1 Answer 1

2

Create your pojo for known fields:

class Attributes {
    private Location location;
    ...
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    ... getters and setters

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

class LibraryBean {
    private String tag;
    private Attributes attributes;

    ... getters and setters
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.