jackson中处理json中键不为双引号的情况

在jackson中,如果要处理如下的情况:

String json = "{name:\"test\"}";

  Map<String,String> map = new HashMap<String,String>();
  ObjectMapper mapper = new ObjectMapper();

  map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){});

会发现出错:
org.codehaus.jackson.JsonParseException:
   Unexpected character ('n' (code 110)): was expecting double-quote to start field name
   at [Source: java.io.StringReader@7c87c24a; line: 1, column: 3]

其实是因为标准json中,要求键和值其实都是要双引号的.
  但如果非要设置键值为非双引号不可的话,则需要设置JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,如下:
String json = "{name:\"mkyong\"}";

Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();

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

try {

map = mapper.readValue(json,
                         new TypeReference<HashMap<String,String>>(){});
System.out.println(map);

}
但当然这是不推荐的哦

你可能感兴趣的:(json)