简体   繁体   中英

Getting error when trying parse JSON string. org.json.JSONException: A JSONArray text must start with '['

I am trying to parse a JSON string so I could turn it into an array and iterate through each element through indexing. Below is my code:

String body = "{\"user\":\"d26d0op3-7da5-6ad8\",\"pass\":\"12784949-2b8c-827d\"}";

ArrayList<String> stringArray = new ArrayList<String>();

JSONArray jsonArray = new JSONArray(body);

for (int i = 0; i < jsonArray.length(); i++) {
    stringArray.add(jsonArray.getString(i));
}

System.out.println(stringArray);

When I run this code, I get the following error:

Exception in thread "main" org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]

I tried formatting my body differently with:

String body = "[{\"user\":\"d26d0op3-7da5-6ad8\",\"instanceId\":\"12784949-2b8c-827d\"}]";

But then I got the following error:

Exception in thread "main" org.json.JSONException: JSONArray[0] is not a String.

How would I go about correctly parsing my JSON?

You might want to read up a bit on the JSON format. Try http://json.org .

In your first case, body is a JSON 'object', not an array. This is similar to a dictionary, or key:value pair map. A JSON object is delimited with { and }.

To parse this body, you would use:

JSONObject job = new JSONObject(body);
String username = job.getString("user");

I think that is probably what you are after.

In the second case, your body is a JSON array that contains one JSON Object. A JSON array is delimited by [ and ]

If you want a JSON array of strings, it would look something like this, instead:

 body = "[ \"a\", \"b\", \"c\" ]";

An array of integers would look like:

 body = "[ 1,2,3,4 ]";

You can use the ObjectMapper.readValue(String, Class<T>) method to parse a value from a json string to some object. In this case it can be a Map<String, String> :

String body = "{\"user\":\"d26d0op3-6ad8\",\"pass\":\"12784949-827d\"}";

Map<String, String> map = new ObjectMapper().readValue(body, Map.class);

System.out.println(map); // {user=d26d0op3-6ad8, pass=12784949-827d}

If you are expecting a list of some objects:

String body = "[{\"user\":\"d26d0op3-6ad8\",\"pass\":\"12784949-827d\"}]";

List<Object> list = new ObjectMapper().readValue(body, List.class);

System.out.println(list); // [{user=d26d0op3-6ad8, pass=12784949-827d}]

The String body = "{"user":"d26d0op3-6ad8","pass":"12784949-827d"}" is not a array enter image description here

you can convert to json array like this String body = "[{"user":"d26d0op3-7da5-6ad8","pass":"12784949-2b8c-827d"}]";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM