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