Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

jackson

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?

like image 687
Max Avatar asked Jul 14 '26 03:07

Max


1 Answers

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.

like image 200
edthethird Avatar answered Jul 17 '26 23:07

edthethird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!