简体   繁体   中英

Can every JSON serializable Java object be represented as a Map<String, Object>?

I have a bunch of Java objects that are being serialized with Jackson. All of the serialized types look something like this:

class MySampleClass {
    @JsonProperty("propName1")
    private MyCustomType propName1;

    @JsonProperty("propName2")
    private MyOtherCustomType propName2;

    @JsonCreator
    public MySampleClass(@JsonProperty("propName1") MyCustomType propName1, @JsonProperty("propName2") MyOtherCustomType propName2) {
        this.propName1 = propName1;
        this.propName2 = propName2;
    }
}

Is there any case where converting instances of this class to a Map<String, Object> and then converting the map to JSON will not be desearializable back into the original Java object?

That'll do it, unless you are receiving an array of these objects. If that's the case, then you can use MySampleClass[] .

JSON is defined in RFC 7159. From here:

An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.

(emphasis mine)

So, a JSON object must have Strings as keys, and values can be one of a handful of Object types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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