Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

619
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda