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?