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

后端 未结 4 1389
悲哀的现实
悲哀的现实 2020-11-30 10:56

As the code below:

public class Main {

    public class innerPerson{
        private String name;
        public String getName(){
            return name;
         


        
相关标签:
4条回答
  • 2020-11-30 11:23

    The "address" that you see printed is simply what your toString() method returns.

    Disregarding the JSON marshaling for now In order for your code to work, you need to implement: equals(), hashCode() and toString() within your InnerPerson class. If you return the name property in toString(), that will become the key in your JSON representation.

    But without proper implementations for equals() and hashCode(), you cannot make proper use of a HashMap.

    0 讨论(0)
  • 2020-11-30 11:27

    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.

    0 讨论(0)
  • 2020-11-30 11:31

    It is possible with Gson library.

    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); gson.toJson(map);

    0 讨论(0)
  • 2020-11-30 11:49

    In addition to existing correct answers, you can also add custom key serializers and key deserializers using Module interface (usually with SimpleModule). This allows you to externally define serialization and deserialization of keys. Either way, keys in JSON must be Strings, like others have pointed out.

    0 讨论(0)
提交回复
热议问题