如下面的代码:使用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"}
是否有可能使地图的关键是准确的数据,但不是对象的唯一解决?怎么样?
几天前我遇到了同样的问题,发现密钥不能成为jackson成功序列化/反序列化映射的pojo。 – 2012-07-24 10:21:19
@ShankhoneerChakrovarty是的,当我想序列化一个复杂的对象时必须小心,因为它可能包含一个以对象作为键的映射结构!真是麻烦! – GMsoF 2012-07-24 12:20:02