Jackson : was expecting double-quote to start field name

摘要: A simple example to use Jackson to convert a JSON string to a Map.

A simple example to use Jackson to convert a JSON string to a Map.

  String json = "{name:\"mkyong\"}";
  Map<String,String> map = new HashMap<String,String>();
  ObjectMapper mapper = new ObjectMapper();
  map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){});

Problem

When the program is executed, it hits following error message

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]
 

Solution

In JSON specification, it requires the use of double quotes for field names. To enable Jackson to handle the unquoted field name, add JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES in the ObjectMapper configuration.

package com.mkyong.jsonexample;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class JsonMapExample {
    public static void main(String[] args) {
	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);
	} catch (JsonParseException e) {
		e.printStackTrace();
	} catch (JsonMappingException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}	

Output

{name=mkyong}
Note
In JSON, unquoted field names are non-standard, and should be avoided.

References

  1. Wikipedia : JSON
  2. JsonParser.Feature JavaDoc

上一篇: Regular Expression case sensitive example Java
下一篇: Windows 8 keeps dropping wifi connection
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章来源于互联网, 若有侵权, 联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布文章.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号