Question

I'm parsing this JSON stream

{
    "status":"ok",
    "count":1,
    "data":{
        "1000194290":[
            {
                "statistics":{
                    "wins":472,
                    "all":{
                        "spotted":0,
                        "hits":0,
                        "battle_avg_xp":0,
                        "draws":0,
                        "wins":472,
                        "losses":0,
                        "capture_points":0,
                        "battles":894,
                        "damage_dealt":0,
                        "hits_percents":0,
                        "damage_received":0,
                        "shots":0,
                        "xp":0,
                        "frags":0,
                        "survived_battles":0,
                        "dropped_capture_points":0
                    },
                    "battles":894
                },
                "mark_of_mastery":4,
                "tank_id":3649
            },
            ...
        ]
    }
}

I attempt to start an array at 1000194290 but get this error

Exception in thread "main" java.lang.IllegalStateException: Expected BEGIN_ARRAY but was NAME at line 1 column 35

My parsing class looks like this

public List<TankStats> readJsonStream(InputStream in) throws IOException {
    try (JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"))) {
        return readTankIdStep(reader);
    }
}

public List<TankStats> readTankIdStep(JsonReader reader) throws IOException {
    List<TankStats> users = new ArrayList<>();
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("data")) {
            reader.beginObject();
            while (reader.hasNext()) {
                reader.beginArray();
                while (reader.hasNext()) {
                    users.add(readTankId(reader));
                 }
                 reader.endArray();
            }
        }   
        else {
            reader.skipValue();
        }   
    }
    reader.endObject();
    return users;
}

I'm not really sure how to get around this error.

Was it helpful?

Solution

You check for the JSON

"data":{

with

if (name.equals("data")) {

Then consume the object in that name value pair with

reader.beginObject();

But then you do this

while (reader.hasNext()) {
    reader.beginArray();

while the token in the reader is

"1000194290":[
        {

You have to first consume the name before you consume the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top