Reputation: 6290
ByteArrayOutputStream result = new ByteArrayOutputStream();
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
Is there a way to determine whether result contains a JSONObject or a JSONArray? I've been blindly casting it to a JSONObject however, i've hit a case where it is a JSONArray - any help would be appreciated.
JSON API: Using faster jackson and org.json
Thanks in advance
Upvotes: 0
Views: 770
Reputation: 3852
These are the Maven dependencies:
<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>
And the code sample:
// 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;
}
(just a sample that works, most probably not the "best")
Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Code sample:
// see JsonNodeType
new ObjectMapper().reader().readTree("[]").getNodeType();
Upvotes: 2