Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report

0

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
about 4 years ago · Santiago Trujillo Report

0

here's how i would do it ..

To validate if a string is JSON

    //isValidJson = false;
    /*try 
    {
    Gson gs = new Gson();
    Object ob = gs.ToJson(yourStringToValidate)
    isValidJson = true;
    }
    catch  
    {
    //do nothing
    }

    isValidXML = false;
    /*try 
    {
    //using JAXB try converting to a Java object
    JAXBContext jaxbContext = JAXBContext.newInstance(Object.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            Object obj = (Object) unmarshaller.unmarshal(YourString/Fileobj);

    isValidXML = true;
    }
    catch  
    {
    //do nothing
    }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!