A user
A user

Reputation: 29

JSON object is not detected correctly

I am trying to detect if my string is a JSON object or a JSON array. Here are my examples:

jsonObject = "{"key":"value1", "id":"1"}";
jsonArray = "[{"key":"value0", "id":"0"},{"key":"value1", "id":"1"}]"

The JSON array is detected correctly but the JSON object is not correct. Here is my code:

import com.jayway.jsonpath.Configuration;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;

public class json {
    public static void main(String[] args) {
        String jsonObject = "{\"key\":\"value1\", \"id\":\"1\"}";
        Object documentObject = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject);
        // Why is documentObject not recognized as an object?
        if (documentObject instanceof JSONArray) {
            System.out.println("jsonObject is JSONArray");
        } else if (documentObject instanceof JSONObject) {
            System.out.println("jsonObject is JSONObject");
        } else {
            System.out.println("jsonObject is UNKNOWN");
        }

        String jsonArray = "[{\"key\":\"value0\", \"id\":\"0\"},{\"key\":\"value1\", \"id\":\"1\"}]";
        Object documentArray = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray);
        // jsonArray is recognized properly
        if (documentArray instanceof JSONArray) {
            System.out.println("jsonArray is JSONArray");
        } else if (documentArray instanceof JSONObject) {
            System.out.println("jsonArray is JSONObject");
        } else {
            System.out.println("jsonArray is UNKNOWN");
        }

    }
}

And the output: jsonObject is UNKNOWN jsonArray is JSONArray

What is wrong?

Upvotes: 0

Views: 1632

Answers (1)

Stephen C
Stephen C

Reputation: 718956

First of all, as @Henry points out, if you want to distinguish between a JSON object and a JSON array, the simple way is to check the first non-whitespace character.

As to why your code doesn't work, it seems that parse(jsonObject) is returning an instance of LinkedHashMap. At least that is what I am seeing for the following versions:

  <dependencies>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
      <groupId>net.minidev</groupId>
      <artifactId>json-smart</artifactId>
      <version>2.3</version>
    </dependency>
  </dependencies>

It turns out that this is the default behavior of the jayway jsonpath library. The default configuration specifies an order-aware representation of the JSON object. With json-smart, that is implemented as a LinkedHashMap.

So, the test for a JSON object (if you do it this way, using these libraries to read your JSON) should be:

    if (object instanceof Map) {
        System.out.println("object is a JSON object");
    }

Upvotes: 2

Related Questions