解析JSON数组BEGIN_ARRAY但是是NAME

时间:2014-04-28 14:00:50

标签: java json gson

我正在解析这个JSON流

{
    "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
            },
            ...
        ]
    }
}

我尝试在1000194290开始一个数组但是得到了这个错误

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

我的解析类看起来像这样

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;
}

我不确定如何解决这个错误。

1 个答案:

答案 0 :(得分:3)

您检查JSON

"data":{

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

然后使用

使用该名称值对中的对象
reader.beginObject();

但是你这样做

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

而读者中的令牌是

"1000194290":[
        {

在使用数组之前,必须首先使用该名称。