'POJO Json object wrapped in double quotes doesn't deserialize to Java
My application is receiving json objects from some source and these are wrapped as strings. These are not getting deserialized but throw exception like mentioned below. I have created a sample program to reproduce this. Can someone points out if there is a way to ignore extra quotes around json fields for it while deserializing or object mapper configuration to make it work.
@Test
void testTrade() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Trade trade = new Trade(2.3, "USD");
String json = mapper.writeValueAsString(trade);
System.out.println(json);
Trade res = mapper.readerFor(Trade.class).readValue(json);
Assertions.assertEquals(trade, res);
String jsonString = "{\"value\":2.3,\"currency\":\"USD\"}";
Trade res1 = mapper.readerFor(Trade.class).readValue(jsonString);
String jsonString2 = "\"{\\\"value\\\":2.3,\\\"currency\\\":\\\"USD\\\"}\"";
//This throws exception : Cannot construct instance of `com....Trade` (although at least one Creator exists):
Trade res2 = mapper.readerFor(Trade.class).readValue(jsonString2);
}
}
class Trade {
double value;
String currency;
@JsonCreator
public Trade(@JsonProperty("value") double value, @JsonProperty("currency") String currency) {
this.value = value;
this.currency = currency;
}
//getters, equals, hashcode, toString()
}
Exception:
Cannot construct instance of `com....Trade` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"value":2.3,"currency":"USD"}')
at [Source: (String)""{\"value\":2.3,\"currency\":\"USD\"}""; line: 1, column: 1]
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com....Trade` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"value":2.3,"currency":"USD"}')
at [Source: (String)""{\"value\":2.3,\"currency\":\"USD\"}""; line: 1, column: 1]
Solution 1:[1]
The Base Answer is from How do I unescape a JSON String using Java/Jackson?
There is an apache common util for unescape strings.
org.apache.commons.text.StringEscapeUtils;
But, in your case, your string has one more problem, you also need to trim the first and last recurring double quotes. Then you can able to apply unescape util upon.
jsonString2 = jsonString2.substring(1, jsonString2.length() - 1);
jsonString2 = StringEscapeUtils.unescapeJava(jsonString2);
Hope it will solve your case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ahmet Orhan |