我们可以在使用JSON时将对象设置为地图中的键吗?

我们可以在使用JSON时将对象设置为地图中的键吗?

问题描述:

如下代码所示:

public class Main {

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


    public static void main(String[] args){
        ObjectMapper om = new ObjectMapper();

        Map<innerPerson, String> map = new HashMap<innerPerson,String>();

        innerPerson one = new Main().new innerPerson();
        one.name = "david";

        innerPerson two = new Main().new innerPerson();
        two.name = "saa";

        innerPerson three = new Main().new innerPerson();
        three.name = "yyy";

        map.put(one, "david");
        map.put(two, "11");
        map.put(three, "true");



        try {
            String ans = om.writeValueAsString(map);

            System.out.println(ans);


        } catch (JsonGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

输出为:

{"Main$innerPerson@12d15a9":"david","Main$innerPerson@10a3b24":"true","Main$innerPerson@e91f5d":"11"}

是否可以使地图的关键字是精确数据而不是对象的地址吗?怎么样?

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


我们可以在使用JSON时将对象作为地图中的键吗?

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

严格来说,没有。 JSON map 数据结构是JSON 对象数据结构,它是名称/值对的集合,其中元素名称必须是字符串。因此,尽管将JSON对象感知并绑定为映射是合理的,但JSON映射键也必须是字符串 - 再次,因为JSON映射是JSON对象。有关JSON对象(映射)结构的规范,请访问 http://www.json.org

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正确描述了Jackson的默认地图密钥序列化程序的行为,它只调用 toString () Java映射键的方法。而不是修改 toString()方法以返回地图密钥的JSON友好表示,使用Jackson实现自定义地图密钥序列化也是可能且相当简单。可以在序列化地图<日期,字符串>中找到这样做的一个示例。与杰克逊

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.