Can we make object as key in map when using JSON?

Can we make object as key in map when using JSON?

Strictly, no. The JSON map data structure is a JSON object data structure, which is a collection of name/value pairs, where the element names must be strings. Thus, though it’s reasonable to perceive and bind to the JSON object as a map, the JSON map keys must also be strings — again, because a JSON map is a JSON object. The specification of the JSON object (map) structure is available at http://www.json.org.

Is it possible to make the key of the map be exact data but not object’s address only? How?

Costi correctly described the behavior of the default map key serializer of Jackson, which just calls the toString() method of the Java map key. Instead of modifying the toString() method to return a JSON-friendly representation of the map key, it’s also possible and reasonably simple to implement custom map key serialization with Jackson. One example of doing so is available at Serializing Map<Date, String> with Jackson.

Leave a Comment