[英]Java check if a string is valid JSON or valid XML or neither
我正在編寫一個函數來檢查輸入字符串是有效的JSON還是有效的XML,或者兩者都沒有。 我在這里發了一個帖子。 但顯然帖子中的答案是不正確的,因為它們只檢查字符串是否以<
或{
開頭,這不能保證字符串是有效的 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:您可以使用此處的 JSONObject。 這是關於它的演示 。
對於XML :如果要檢查格式良好的XML,則應該使用DocumentBuilder 。 演示:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(XmlSourceFile);
嘗試解析,如果沒有失敗,你就可以使用XML了。 根據您的適用性嘗試重載dBuilder.parse()
重載方法
這是我怎么做的..
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.