In below Java TestCase I have invalid JOSN ('input' variable Value), meaning its not strict JOSN object. I want mapper.readValue to return input String as is. Below test case print "{StrKey1=StrValue1}" on console. mapper.readValue does not throw an exception but pick first JOSN item and convert it into Map. I have to keep Map.class as Value Type because following logic is depend on that if converted value is Map.
@Test
public void testInvalidJson() {
String input = "{\"StrKey1\":\"StrValue1\"},{\"StrKey2\":\"StrValue2\"}";
ObjectMapper mapper = new ObjectMapper();
try {
Object map = mapper.readValue(input, Map.class);
System.out.println(map);
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I dont want to set DeserializationFeature.FAIL_ON_TRAILING_TOKENS on ObjectMapper as my inputs are expected to be invalid JSON as well as non strict JSON and those should be converted to String. Even org.json.JSONObject("{"StrKey1":"StrValue1"},{"StrKey2":"StrValue2"}") does not throw an exception.
What changes I should make in above code so that mapper.readValue will return complete input string as output for given input?
CodePudding user response:
You may want to check first whether the json is valid using the below code, The nextToken verifies if the json is valid, if not you can return the input string as is, it is already a string.
public void testInvalidJson() {
String input = "{\"StrKey1\":\"StrValue1\"},{\"StrKey2\":\"StrValue2\"}";
JsonParser jp = mapper.getFactory().createParser(input);
try {
Object map = mapper.readValue(jp, Map.class);
while (jp.nextToken() != null) {
//return the source string
//System.out.println(input);
}
System.out.println(map);
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CodePudding user response:
To deal with invalid JSON, you need either:
to fix it, i.e. modify the input so that it would be valid;
write your own parser.
In case if it's simple Map<String,String>
, then you can fix it by removing redundant curly braces. Otherwise, if there are some nested levels, i.e. some of this curly braces should stay in place, then it's most likely irreparable.
Here's an example with your sample data:
String input = "{\"StrKey1\":\"StrValue1\"},{\"StrKey2\":\"StrValue2\"}";
String normalized = '{' input.replaceAll("[{}]", "") '}';
Map<String, String> map = mapper.readValue(normalized, new TypeReference<LinkedHashMap<String, String>>() {});
System.out.println(map);
Output:
{StrKey1=StrValue1, StrKey2=StrValue2}