0
我創建了一個將HashMap對象轉換爲String的應用程序,它的工作正常,我面臨的問題是我想將HashMap字符串再次轉換回HasMap對象,當我嘗試通過使用下面的代碼,我得到的異常,如下面將Java字符串轉換爲HashMap對象
Unexpected character ('u' (code 117)): was expecting double-quote to start field name
誰能告訴我,這
一些解決方案如下
Map<String,Object> map = new HashMap<String,Object>();
map.put("userVisible", true);
map.put("userId", "1256");
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(map.toString(), new TypeReference<HashMap<String,Object>>(){});
System.out.println(map.get("userId"));
} catch (Exception e) {
e.printStackTrace();
}
我的代碼給出10
更新1
正如@chrylis建議我用像如下圖所示Feature.ALLOW_UNQUOTED_FIELD_NAMES,但現在我得到以下異常
Unexpected character ('=' (code 61)): was expecting a colon to separate field name and value
更新的代碼
Map<String,Object> map = new HashMap<String,Object>();
map.put("userVisible", true);
map.put("userId", "1256");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
try {
map = mapper.readValue(map.toString(), new TypeReference<HashMap<String,Object>>(){});
System.out.println(map.get("userId"));
} catch (Exception e) {
e.printStackTrace();
}
越來越'意外的字符('='(代碼61)):期待一個冒號分隔字段名稱和值' – 2014-10-28 06:37:37
你能告訴我一個例子 – 2014-10-28 06:41:43
@AlexMan字符串json = mapper.writeValueAsString(map); – StaxMan 2014-10-29 21:13:05