I have a JSON array that I want to make sure only contains strings. Jackson implicitly casts integers and dates to strings. I want to make sure that every element in the JSON array is in fact a string.
Object[] badModuleArray = new Object[]{"case", 1, 2, "employee", new Date()};
ObjectMapper objectMapper = new ObjectMapper();
String jsonModules = objectMapper.writeValueAsString(badModuleArray);
try
{
TypeFactory typeFactory = TypeFactory.defaultInstance();
mapper.readValue(modules, typeFactory.constructCollectionType(List.class, String.class));
}
catch(IOException e)
{
logger.error("something other than strings in JSON object");
}
In the above example, I want the ObjectMapper to not cast integer, dates, etc to Strings. I want an exception thrown if each element in the JSON array is not a string. Is this possible?
Jackson is casting each object to a string because you’ve told it that you want a
List<String>.Instead, ask Jackson for a
List<Object>and examine the contents of the List yourself to throw an error if any of them are not a String:For JSON of
["case",1,2,"employee",1358444552861]I get: