0

我有这个 .json 类型

{"paging":{"page":1,"total":2015,"page_size":20,"pages":101},

"loans":[
    {
    "id":519729,
    "name":"Hefseba Group",
    "description":{"languages":["en"]},
    "status":"fundraising",
    "funded_amount":3125,
    "basket_amount":0,
    "image":{"id":1280581,"template_id":1},
    "activity":"Cafe",
    "sector":"Food",
    "use":"to buy more stock for her cafe, and to buy more fabrics and liquid soap.",
    "location":{"country_code":"TZ",
    "country":"Tanzania",
    "geo":{"level":"country","pairs":"-6 35","type":"point"}},
    "partner_id":87,
    "posted_date":"2013-02-01T09:14:17Z",
    "planned_expiration_date":"2013-03-03T09:14:17Z",
    "loan_amount":4025,
    "borrower_count":16
    },

    {
    "id":520550,"name":"Waridi Pendo Group",
    "description":{"languages":["en"]},
    "status":"fundraising",
    "funded_amount":800,
    "basket_amount":0,
    "image":{"id":1282077,"template_id":1},
    "activity":"Music Discs & Tapes",
    "sector":"Retail",
    "use":"to buy music equipment and DVDs and CDs, as well as to start building his house. ",
    "location":{"country_code":"TZ",
    "country":"Tanzania",
    "geo":{"level":"country","pairs":"-6 35","type":"point"}},
    "partner_id":87,
    "posted_date":"2013-02-01T09:18:11Z",
    "planned_expiration_date":"2013-03-03T09:18:11Z",
    "loan_amount":6100,
    "borrower_count":11
    }
]

}

然后我有这段代码试图解析它。

try{
    JsonReader runThrough = getJsonReader(fileName);
    System.out.println("File found");
    Gson myGson = new Gson();
    JsonParser jsonParser = new JsonParser();
    JsonArray infoArray =  jsonParser.parse(runThrough).getAsJsonArray();
    System.out.println("Finished Parsing");
    for (JsonElement piece : infoArray){

    }
} catch (Exception e){
    System.out.println(e);
}

我希望每笔贷款最终都保存到 kLoan 的数组列表中,但我现在只有一个空循环。我得到的错误冻结在这一行:

JsonArray infoArray =  jsonParser.parse(runThrough).getAsJsonArray();
4

1 回答 1

1
  1. 它不是有效的 JSON 文件。所以也许这就是解析器卡住的原因。有关详细信息,请使用 JSON lint 检查。少了一个逗号。

  2. 整个对象不是数组。您需要获得财产贷款并在此元素上调用 getAsJsonArray 方法。像这样:

    try{
        JsonReader runThrough = getJsonReader(fileName);
        System.out.println("File found");
        Gson myGson = new Gson();
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObj =  jsonParser.parse(runThrough).getAsJsonObject();
        JsonArray infoArray = jsonObj.getAsJsonArray("loans");
        System.out.println("Finished Parsing");
        for (JsonElement piece : infoArray){
    
        }
    } catch (Exception e){
        System.out.println(e);
    }
    
于 2013-02-05T18:58:27.343 回答