I am writing a function to check if the input string is valid JSON or valid XML or neither. I found a post here. But obviously the answers in the post are incorrect because they only check if the string starts with <
or {
, which cannot guarantee the string is valid JSON or valid XML.
I do have a solution myself, which is:
public static String getMsgType(String message) {
try {
new ObjectMapper().readTree(message);
log.info("Message is valid JSON.");
return "JSON";
} catch (IOException e) {
log.info("Message is not valid JSON.");
}
try {
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(message)));
log.info("Message is valid XML.");
return "XML";
} catch (Exception e) {
log.info("Message is not valid XML.");
}
return null;
}
I am wondering if there is any better or shorter solution? Thanks.