简体   繁体   English

从 JSONArray 获取数据

[英]Get data from JSONArray

I'm trying to parse data from my json with the following kotlin code:我正在尝试使用以下 kotlin 代码解析来自我的json的数据:

val text = JSONObject(URL(request).readText())
val results = text.getJSONArray("results")
val name = results.getJSONObject(5).getString("name") // org.json.JSONException: Index 5 out of range [0..1) 

json json

{
    summary: {
    queryType: "NEARBY",
    queryTime: 13,
    numResults: 2,
    offset: 0,
    totalResults: 2,
    fuzzyLevel: 1,
    geoBias: {
        lat: -37.736343,
        lon: 145.152114
        }
    },
    results: [
    {
    type: "POI",
    id: "AU/POI/p0/77255",
    score: -0.38554,
    dist: 385.5365152133808,
    info: "search:ta:0323405846509-AU",
    poi: {
        name: "La Gourmet",

However I'm getting the following error on my 3rd line:但是我在第三行收到以下错误:

org.json.JSONException: Index 5 out of range [0..1)

I'm not sure why I'm getting this error.我不确定为什么会收到此错误。 I resorted to searching for name via index because .getJSONObject("poi") doesn't take a String .我求助于通过索引搜索name ,因为.getJSONObject("poi")不采用String This is also concerning because the data may change so I would prefer to query the JSON via String .这也令人担忧,因为数据可能会发生变化,所以我更愿意通过String查询JSON

Any idea?任何想法?

results is an array, and your code tries to get the 5th element of the array. results是一个数组,您的代码尝试获取数组的第 5 个元素。 You need to get the first element, and then you can get poi by name.需要先获取第一个元素,然后才能通过名字获取poi

val text = JSONObject(URL(request).readText())
val results = text.getJSONArray("results")
val result0 = results.getJSONObject(0)
val poi = result0.getJSONObject("poi")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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