简体   繁体   中英

Can't parse some JSON into a JsonArray using GSON

I am trying to get the values from a JSON response. I got everything to work, except extracting an array from the following string:

{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}

I know GSON is trying to parse it because I get this error:

Exception in thread "main" java.lang.IllegalStateException: Not a JSON Array: {"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}

I am using the following code to attempt to parse it:

final JsonElement midElement = obj.get("mid");
        final JsonArray midArray = midElement.getAsJsonArray();
        for(Object rate : midArray){
            final JsonObject rateObj = (JsonObject)rate;
            final JsonElement openElement = rateObj.get("o");
            open = openElement.getAsFloat();

            final JsonElement highElement = rateObj.get("h");
            high = highElement.getAsFloat();

            final JsonElement lowElement = rateObj.get("l");
            low = lowElement.getAsFloat();

            final JsonElement closeElement = rateObj.get("c");
            close = closeElement.getAsFloat();
        }

First of all it doesn't look like a valid JSON array. It should look like this

[{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}]

Try this following code to parse it in JSON format.

   JSONObject jsonObject = new JSONObject(jsonString);
   JSONArray jsonArray = jsonObject.getJSONArray("mid");
   for (int i = 0; i < jsonArray.length(); i++) {             
         jsonArray.getJSONObject(i).getString("o");
    }

Then convert it your preferred data form.

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