Zorgan
Zorgan

Reputation: 9123

Get data from JSONArray

I'm trying to parse data from my json with the following kotlin code:

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

{
    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. This is also concerning because the data may change so I would prefer to query the JSON via String.

Any idea?

Upvotes: 0

Views: 288

Answers (1)

Matthew Pope
Matthew Pope

Reputation: 7679

results is an array, and your code tries to get the 5th element of the array. You need to get the first element, and then you can get poi by name.

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

Upvotes: 2

Related Questions