确定ByteArrayOutputStream是JSONArray还是JSONObject类型?

时间:2017-05-14 23:47:18

标签: java json inputstream bytearrayoutputstream

ByteArrayOutputStream result = new ByteArrayOutputStream();
while ((length = inputStream.read(buffer)) != -1) {
        result.write(buffer, 0, length);
}

有没有办法确定结果是包含JSONObject还是JSONArray?我一直盲目地把它投射到JSONObject但是,我遇到了一个JSONArray的情况 - 任何帮助都会受到赞赏。

JSON API:使用更快的jackson和org.json

提前致谢

1 个答案:

答案 0 :(得分:2)

JSR 353参考实现

请参阅https://jsonp.java.net/

这些是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 Jackson

(只是一个有效的样本,很可能不是“最好的”)

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();