2014-10-28 255 views
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(); 
} 

回答

2

你会得到这个错误,因为JSON指定你必须将字段名称放在引号中,而不像普通的JavaScript对象。你可以告诉杰克逊通过配置ObjectMapper因此要允许不带引号的字段名称:

mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); 

更新

看来,更根本的问题是,你试图使用Java的toString()转换到String的地图以及Jackson JSON映射器将其转换回来。这两种格式完全不同,如果您需要能够将字符串转换回对象,则应该首先使用Jackson映射器将映射转换为JSON。

+0

越来越'意外的字符('='(代码61)):期待一个冒号分隔字段名称和值' – 2014-10-28 06:37:37

+0

你能告诉我一个例子 – 2014-10-28 06:41:43

+1

@AlexMan字符串json = mapper.writeValueAsString(map); – StaxMan 2014-10-29 21:13:05