如下面的代碼:使用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