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.
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
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:
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
}