判断 ByteArrayOutputStream 是 JSONArray 还是 JSONObject 类型?
determine whether ByteArrayOutputStream is of type JSONArray or JSONObject?
ByteArrayOutputStream result = new ByteArrayOutputStream();
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
有没有办法确定结果是否包含 JSONObject 或 JSONArray?我一直在盲目地将它投射到 JSONObject 但是,我遇到了一个 JSONArray 的情况 - 任何帮助将不胜感激。
JSON API: 使用更快的 jackson 和 org.json
提前致谢
JSR 353 参考实现
这些是 Maven 依赖项:
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
<scope>runtime</scope>
</dependency>
代码示例:
// the JSON classes have package javax.json
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// read JSON into baos
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
InputStreamReader isr = new InputStreamReader(bais, Charset.forName("UTF-8"));
JsonReader jr = Json.createReader(isr);
JsonStructure js = jr.read();
switch (js.getValueType()) {
case ARRAY:
break;
case OBJECT:
break;
case STRING:
break;
case NUMBER:
break;
case TRUE:
break;
case FALSE:
break;
case NULL:
break;
}
FasterXML 杰克逊
(只是一个有效的示例,很可能不是 "best")
Maven 依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
代码示例:
// see JsonNodeType
new ObjectMapper().reader().readTree("[]").getNodeType();
ByteArrayOutputStream result = new ByteArrayOutputStream();
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
有没有办法确定结果是否包含 JSONObject 或 JSONArray?我一直在盲目地将它投射到 JSONObject 但是,我遇到了一个 JSONArray 的情况 - 任何帮助将不胜感激。
JSON API: 使用更快的 jackson 和 org.json
提前致谢
JSR 353 参考实现
这些是 Maven 依赖项:
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
<scope>runtime</scope>
</dependency>
代码示例:
// the JSON classes have package javax.json
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// read JSON into baos
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
InputStreamReader isr = new InputStreamReader(bais, Charset.forName("UTF-8"));
JsonReader jr = Json.createReader(isr);
JsonStructure js = jr.read();
switch (js.getValueType()) {
case ARRAY:
break;
case OBJECT:
break;
case STRING:
break;
case NUMBER:
break;
case TRUE:
break;
case FALSE:
break;
case NULL:
break;
}
FasterXML 杰克逊
(只是一个有效的示例,很可能不是 "best")
Maven 依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
代码示例:
// see JsonNodeType
new ObjectMapper().reader().readTree("[]").getNodeType();