0

Good morning,

I'm currently coding on android (kotlin), and I'm trying to parse a json file with the url.

Everything is working fine when it comes with the request, but since the json is a little bit tricky, I can't seem to find a way to get my informations properly.

Every time I get a JSON exeption error or an error telling me that the array is not a primitive one.

This is the essential part of my code were the magic happens.

try {
            // Create JSONObject from string response if your response start from Array [ then create JSONArray
            val rootJsonObject = JSONObject(results)
            val isSucess = rootJsonObject.optString("code")

            if (isSucess == "200") {

                val streetArray = rootJsonObject.getJSONObject("data").getJSONObject("nearstations")
                val mJsonArray = JSONArray(streetArray)

                for (i in 0 until mJsonArray.length()) {

                    val sObject = mJsonArray.getJSONObject(i).toString()
                    val mItemObject = JSONObject(sObject)

                    val id = mItemObject.getString("id")
                    val street_name = mItemObject.getString("street_name")


                    val mHash = HashMap<String, String>()

                    mHash["id"] = "Id: $id"
                    mHash["street_name"] = "Name: $street_name"

                    streetList.add(mHash)
                }

                // This is simple Adapter (android widget) for ListView
                val simpleAdapter = SimpleAdapter(
                    applicationContext, streetList,
                    R.layout.simple_listview_item,
                    // Add String[] name same as HashMap Key
                    arrayOf("id", "street_name"),
                    intArrayOf(R.id.tv_id, R.id.tv_street_name))

                Lv_client.adapter = simpleAdapter

                Lv_client.setOnItemClickListener { parent, view, position, id ->
                    Toast.makeText(applicationContext, "Selected item is " + position, Toast.LENGTH_SHORT).show()
                }

            }

This is a small part of the JSON from the following (http://barcelonaapi.marcpous.com/bus/nearstation/latlon/%2041.3985182/2.1917991/1.json)

"code": 200,
  "data": {
    "nearstations": [
      {
        "id": "1",
        "street_name": "Almogàvers-Àvila",
        "city": "BARCELONA",
        "utm_x": "432542,5460",
        "utm_y": "4583524,2340",
        "lat": "41.3985182",
        "lon": "2.1917991",
        "furniture": "Pal",
        "buses": "06 - 40 - 42 - 141 - B25 - N11",
        "distance": "0"
      },
      {
        "id": "2721",
        "street_name": "Àvila-Almogàvers",
        "city": "BARCELONA",
        "utm_x": "432641,0420",
        "utm_y": "4583509,2710",
        "lat": "41.3985182",
        "lon": "2.1917991",
        "furniture": "Pal",
        "buses": "92",
        "distance": "0"
      },

1 Answer 1

3

First thing is you never actually asked a question. You said that there was a problem but never specified where. One thing I noticed is that you're checking the value of isSucess as a String, the json link shows the code is returned as a numerical value. - Use optInt instead of optString and then remove the double quotes around the if condition may help you along.

if (isSucess == 200) {

However, I think you could simplify your task greatly by using a library which deals with the parsing of the json response automatically and then return a model of the response in the form of data objects.

One such library is gson. You'd use it as follows..

val rootJsonObject = Gson().fromJson(json, RootJsonObject::class.java)

To begin with you'd need to declare your data model classes :

data class RootJsonObject(
    val code: Int,
    val data: DataJsonObject
)

data class DataJsonObject(
    val nearstations: List<NearStation>
)

data class NearStation(
    val id: String,
    val street_name: String,
    val city: String,
    val utm_x: String,
    val utm_y: String,
    val lat: String,
    val lon: String,
    val furniture: String,
    val buses: String,
    val distance: String
)

Then you'd parse the json like this :

val rootJsonObject = Gson().fromJson(json, RootJsonObject::class.java)
if (rootJsonObject.code != 200) {
    return
}

And you would use the rootJsonObject.data.nearstations variable as the adapters list.

Hope this helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much, I'm gonna look into it immediately :)
HEY! It finally worked! Thank you! So hum, how can I post the modifications I made for other people?
awesome. you could just post a response to your question stating what you did to resolve the problem. Good Work!
Okay Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.