Reputation: 4886
I have created an application for converting the HashMap object to String, its working fine, The problem which i am facing is that i want to convert the HashMap string again back to HasMap object, when i tried that by using the following code , I am getting exception as shown below
Unexpected character ('u' (code 117)): was expecting double-quote to start field name
Can anyone please tell me some solution for this
My code is given below
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();
}
Update 1
As suggested by @chrylis I have used Feature.ALLOW_UNQUOTED_FIELD_NAMES like as shown below, but now i am getting the following exception
Unexpected character ('=' (code 61)): was expecting a colon to separate field name and value
Updated Code
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();
}
Upvotes: 0
Views: 4370
Reputation: 77187
You're getting this error because JSON specifies that you have to put field names in quotation marks, unlike in a regular JavaScript object. You can tell Jackson to permit unquoted field names by configuring the ObjectMapper
so:
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
Update
It appears that a more fundamental problem is that you're trying to use Java toString()
to convert the map to a String
, and a Jackson JSON mapper to convert it back. The two are completely different formats, and if you need to be able to convert the string back into an object, you should probably use the Jackson mapper to turn the map into JSON in the first place.
Upvotes: 2