简体   繁体   English

将字符串转换为Java中的Map

[英]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 我正在使用杰克逊Objectmapper将对象转换为字符串并将其保存为varchar2到数据库中。我的代码是

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 它作为Varchar2保存到数据库中。但是当我从数据库中检索此值并想使用ObjectMapper将其转换为Map时,它无法执行此操作。它给出了这样的异常

"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. obj是数据库值,它是string.this是我要从中转换地图的字符串。

"\"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 . 之所以失败是因为您要反序列化的String不是有效的json ,因此需要将其包装在花括号中才能使其成为有效的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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