2012-07-24 63 views
15

如下面的代码:使用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(); 
     } 

    } 

} 

输出是:

{"[email protected]":"david","[email protected]":"true","[email protected]":"11"} 

是否有可能使地图的关键是准确的数据,但不是对象的唯一解决?怎么样?

+0

几天前我遇到了同样的问题,发现密钥不能成为jackson成功序列化/反序列化映射的pojo。 – 2012-07-24 10:21:19

+0

@ShankhoneerChakrovarty是的,当我想序列化一个复杂的对象时必须小心,因为它可能包含一个以对象作为键的映射结构!真是麻烦! – GMsoF 2012-07-24 12:20:02

回答

23

使用JSON时,我们可以使对象成为地图中的关键吗?

严格来说,没有。 JSON 数据结构是JSON 对象数据结构,它是名称/值对的集合,其中元素名称必须是字符串。因此,尽管感知并绑定到JSON对象是一个地图是合理的,但JSON地图键也必须是字符串 - 同样,因为JSON地图是JSON对象。 JSON对象(地图)结构的规范可在http://www.json.org处获得。

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

Costi正确地描述了Jackson的默认映射键串行器的行为,它只是调用Java映射键的toString()方法。与其修改toString()方法以返回JSON友好型地图关键字表示法,还可以使用Jackson实现自定义地图关键字序列化。其中一个例子是Serializing Map<Date, String> with Jackson

1

您看到的“地址”打印只是您的toString()方法返回的内容。

忽视的JSON编组现在为了使您的代码工作,你需要实现:equals(),你InnerPerson类中hashCode()toString()。如果您返回toString()中的name属性,那么这将成为JSON表示中的关键字。

但是如果没有适当的实现equals()hashCode(),你不能正确使用HashMap。

1

除了现有的正确答案,您还可以使用Module接口(通常使用SimpleModule)添加自定义键序列化程序和键解串器。这使您可以在外部定义密钥的序列化和反序列化。无论哪种方式,JSON中的键必须是字符串,就像其他人指出的那样。

相关问题