我正在编写一个函数来检查输入字符串是有效的 JSON 还是有效的 XML,或者两者都不是。我找到了一个帖子 here .但显然帖子中的答案是不正确的,因为他们只检查字符串是否以 <
开头。或 {
,这不能保证字符串是有效 JSON 或有效 XML。
我自己有一个解决方案,就是:
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;
}
我想知道是否有更好或更短的解决方案?谢谢。
最佳答案
首先,我认为您不必重新编写 JSON 或 XML 验证代码。它已经可用、经过充分测试并且经过了充分优化。
如果是 JSON: 您可以使用 Here 中的 JSONObject .这是 demo
如果是 XML:您可能应该使用 DocumentBuilder 如果您想检查格式正确的 XML。演示:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(XmlSourceFile);
尝试解析,如果没有失败,您就可以使用 XML 了。尝试
dBuilder.parse()
的重载方法根据你的适用性
关于Java 检查一个字符串是有效的 JSON 还是有效的 XML 或者两者都不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43398363/