简体   繁体   中英

converting string to to Map in Java

I am converting a object into string using jackson Objectmapper and saving it into database as a varchar2.My code is

AuditDataLog dataLog = new AuditDataLog();
ObjectMapper mapper = new ObjectMapper();
dataLog.setData(mapper.writeValueAsString(obj));

it is saved into database as a Varchar2.but when i retrieve this value from data base and want to convert it into Map using ObjectMapper it can't do that.it gives exception like this

"com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [map type; class java.util.HashMap"

Here is my code

Map map = mapper.readValue(obj,HashMap.class));

obj is database value which is string.this is string from which i want to convert map.

"\"MerOrder\":{\"cusAccPartyId\":\"4632\",\"cusAccParty\":{\"fullName\":\"Kariban\"},\"merAccPartyId\":\"4800\",\"merAccParty\":{\"fullName\":\"Golam Sarwer\"},\"season\":\"a455\",\"tfReceiveDate\":\"26 Apr 2017\",\"styleName\":\"a123\",\"styleNo\":\"s345\",\"sizeRange\":\"1\",\"merVariantValue\":{\"name\":\"XL-XS\"}}"

What should I do??

The reason why it fails becuase the String you are trying to deserialise is not a valid json , you need to wrap it into curly braces in order to make it a valid json . Below should work fine:

String s = "\"MerOrder\":{\"cusAccPartyId\":\"4632\",\"cusAccParty\":{\"fullName\":\"Kariban\"},\"merAccPartyId\":\"4800\",\"merAccParty\":{\"fullName\":\"Golam Sarwer\"},\"season\":\"a455\",\"tfReceiveDate\":\"26 Apr 2017\",\"styleName\":\"a123\",\"styleNo\":\"s345\",\"sizeRange\":\"1\",\"merVariantValue\":{\"name\":\"XL-XS\"}}";
ObjectMapper mapper = new ObjectMapper();
HashMap value = mapper.readValue("{" + s + "}", HashMap.class);
System.out.println(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM