Java 检查字符串是否包含 xml 或 json 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20677148/
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
Check if string either contains xml or json data
提问by Shahid Ghafoor
I receive a String which contains either xml or json contents.
我收到一个包含 xml 或 json 内容的字符串。
If String contains json content I use Hymanson(java api) to Convert JSON to Java object
如果 String 包含 json 内容,我使用 Hymanson(java api) 将JSON转换为 Java 对象
And if it contains xml contents I use JAXB to Convert XML content into a Java Object(Unmarshalling).
如果它包含 xml 内容,我使用 JAXB 将 XML 内容转换为 Java 对象(解组)。
How can I check whether I receive xml or json in that string?
如何检查我是否在该字符串中收到 xml 或 json?
回答by Matthias
If the encoding of that string is known to you (or is ASCII or UTF), then looking at the very first char of that String should be enough.
如果您知道该字符串的编码(或者是 ASCII 或 UTF),那么查看该字符串的第一个字符就足够了。
If the String starts
如果字符串开始
- with
<
you have XML structure. - with
{
,[
or other allowed start charactersyou have a JSON structure.
- 与
<
你的XML结构。 - 与
{
,[
或其他允许开始字符你有一个JSON结构。
For JSON you also have to strip whitespace before you look at the "first" char (if the String you receive may contain additional whitespace).
对于 JSON,您还必须在查看“第一个”字符之前去除空格(如果您收到的字符串可能包含额外的空格)。
While it is legal for JSON data structures to begin with null
, true
, false
you can avoid those situations if you already know a bit about your data structures.
虽然它是合法的JSON数据结构首先null
,true
,false
你能避免这些情况,如果你已经知道了一些关于你的数据结构。
So, basically you could check if the 1st char is a <
and in that case treat it as XML. In other cases treat it as JSON and let Hymansonfire some exceptions if it is not legal JSON syntax.
因此,基本上您可以检查第一个字符是否为 a <
,在这种情况下将其视为 XML。在其他情况下,将其视为 JSON,如果它不是合法的 JSON 语法,则让Hymanson触发一些异常。
回答by Michael Kay
An XML document entity (in common parlance, an XML document) must start with "<".
XML 文档实体(一般来说,XML 文档)必须以“<”开头。
A JSON text, according to ECMA-404, starts with zero or more whitespace characters followed by one of the following:
根据 ECMA-404,JSON 文本以零个或多个空白字符开头,后跟以下内容之一:
{ [ " 0-9 - true false null
So your simplest approach is just to test if(s.startsWith("<")
所以你最简单的方法就是测试 if(s.startsWith("<")