Java 检查字符串是否是有效的 JSON 或有效的 XML 或两者都不是

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43398363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:24:03  来源:igfitidea点击:

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

javajsonxml

提问by 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 validJSON or validXML.

我正在编写一个函数来检查输入字符串是有效的 JSON 还是有效的 XML 或两者都不是。我在这里找到了一个帖子。但显然帖子中的答案是不正确的,因为他们只检查字符串是否以<或开头,{不能保证字符串是有效的JSON 或有效的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.

我想知道是否有更好或更短的解决方案?谢谢。

采纳答案by 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)

您是对的,要真正查看某些内容是 json 还是 xml,您必须尝试将其解析为这样 - 对此没有“扁平字符串”解决方案(请参阅此处非常著名的相关问题)

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
  1. 看来您正在使用生成 DOM 树的 json 解析器。这意味着您最终会在内存中得到一个代表 json 的对象树,而您只想查看它是否有效的 json。使用流式 json(参见此处),您可以获得相同的结果,但内存开销较低(实际上没有创建树)
  2. 我不知道 parseXML 做了什么,但它可能遇到与上面相同的问题

回答by Preetam Kumar

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.

首先,我认为您不必为 JSON 或 XML 验证重新编写代码。它已经可用,经过充分测试并经过充分优化。

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

在 JSON 的情况下:您可以使用 JSONObject from Here。这是演示

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

在 XML 的情况下:如果您想检查格式正确的 XML,您可能应该使用DocumentBuilder。演示:

    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

尝试解析,如果没有失败,您就可以使用 XML。dBuilder.parse()根据您的适用性尝试重载的方法

回答by Ashish Madkaikar

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
    }