Java check if a string is valid JSON or valid XML or neither

6324 :

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.

radai :

youre right in that to really see if something is json or xml you must try and parse it as such - there's no "flat string" solution to this (see very famous related question here)

the only area of improvement i could think of here is in performance of the parsing:

  1. it appears youre using a json parser that produces a DOM tree. that means that you end up with an object tree in memory representing the json, when all you wanted was to see if its valid json or not. using streaming json (see here) you could get the same results with a lower memory overhead (no tree actually created)
  2. i dont know what parseXML does but it likely suffers the same issue as above

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437691&siteId=1