JsonMappingException no single-String constructor/

2020-03-12 10:23发布

问题:

I am trying to parse JSON data being sent from UI in my Controller using Spring build Jackson support and this is my code

final Map<String, CartDataHelper> entriesToUpdateMap = new ObjectMapper().readValue(entriesToUpdate, new TypeReference<Map<String, CartDataHelper>>()

my JSON string is

{"0":"{\"categoryCode\":\"shoes\",\"productCode\":\"300050253\",\"initialQty\":\"3\",\"leftoverQty\":\"0\",\"newQty\":\"3\"}",
"1":"{\"categoryCode\":\"shoes\",\"productCode\":\"300050254\",\"initialQty\":\"3\",\"leftoverQty\":\"0\",\"newQty\":\"3\"}"}

i checked the JSON format using some online services and it seems valid, while tryin gto parse JSON data i am getting following exception

org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class controllers.util.CartDataHelper] from JSON String; no single-String constructor/factory method

my CartDataHelper class contains simple properties for for productCode, categoryCode etc with a no argument constructor

回答1:

As comments mentioned, your JSON contains Map<String,String> and NOT Map<String,CartDataHelper>: values are JSON Strings, not JSON Objects.

Ideally you would not try writing out objects as JSON Strings; and if so, things would work.



回答2:

It seems that on the client side the json is sent as a string instead as an object. That way on the server side you are receiveing a string and not a CartDataHelper as you pretend.

Try sending JSON.parse(stringCartDataHelper). It worked for me with the same issue.