簡體   English   中英

Java檢查字符串是有效的JSON還是有效的XML,或者兩者都不是

[英]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你必須嘗試解析它 - 這里沒有“扁平字符串”的解決方案(請參閱這里非常着名的相關問題)

我能想到的唯一改進方面是解析的性能:

  1. 看來你正在使用一個生成DOM樹的json解析器。 這意味着你最終得到一個代表json的內存中的對象樹,當你想要的是看它是否有效的json。 使用流json(參見此處 ),您可以獲得相同的結果,內存開銷較低(實際上沒有樹創建)
  2. 我不知道parseXML做了什么,但它可能遇到與上面相同的問題

首先,我不認為你必須重新發明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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM