Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

xml

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.

like image 776
6324 Avatar asked Apr 13 '17 17:04

6324


People also ask

How to check if a string is a valid JSON string?

JavaScript | Check if a string is a valid JSON string. In order to check the validity of a string whether it is a JSON string or not, We’re using the JSON.parse () method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string. A reviver function may be provided to do a change on ...

Should I use Gson or Jackson for object validation?

While the JSON API can be used for simple object validation, the Gson can be more extensible for raw value validation as part of a JSON object. However, the Jackson is easier to use. Therefore, we should use the one that fits better. Also, we should check if some library is already in use or applies for the rest of the goals as well.

How to check if string is JSON or not in Maven?

A very basic idea is we can parse the string and catch the exception if any exception occurs during parsing. Basically, we can use the org.json JSON API implementation for the check String is JSON or not. We will use the Maven dependency of it and the below code is the dependency code of it.

What is the difference between Gson and jsonparser?

The main difference of this approach is that the Gson default strategy considers separate string and numeric values to be valid as part of the JsonElement node. In other words, it considers a single string or number as valid as well. However, if we want to consider such values as malformed, we need to enforce a strict type policy on our JsonParser.


2 Answers

First of all I dont think you have to reinvent the code for JSON or XML validation. It is already available, well tested and quite optimized.

In case of JSON: you can use JSONObject from Here. Here's demo on that.

In case of XML:You should probably use a DocumentBuilder if you want to check the well formed XML. Demo:

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(XmlSourceFile);

Try parsing, if it does not fail you got good to go XML. try overloaded methods of dBuilder.parse() according to your suitability

like image 140
Preetam Kumar Avatar answered Oct 16 '22 13:10

Preetam Kumar


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
like image 4
radai Avatar answered Oct 16 '22 12:10

radai