0

I got this error when I am trying to get JSONArray arrivals

Here is my json :

{
  "arrivals": [
    {
      "airline": "Iraqi Airways",
      "alia": "Iraqi Airways IAW",
      "flight": "IA136"
    }
  ]
}

my code :

private fun handleJson (jsonString: String?){

        val jsonObj = JSONArray("arrivals")
        val list =  ArrayList<FlightShdu>()
        var x = 0
        while (x < jsonObj.length()){

            val jsonObject = jsonObj.getJSONObject(x)

            list.add(FlightShdu(

                jsonObject.getInt("airline"),
                jsonObject.getString("fn")

            ))


            x++
        }
        val adapter = ListAdapte(this@MainActivity,list)
        flightShdu_list.adapter = adapter

    }
Mukyuu
  • 6,436
  • 8
  • 40
  • 59
Ali Ghassan
  • 1,280
  • 1
  • 22
  • 59
  • can you give me example please , l am new in kotlin .@Enzokie – Ali Ghassan Nov 05 '18 at 06:42
  • You can check this sample question https://stackoverflow.com/questions/5566669/how-to-parse-a-json-object-in-android Although it is Java base but you can apply that in Kotlin (just minor syntax difference). – Enzokie Nov 05 '18 at 07:18

1 Answers1

0

I could not understand your code and wrote it alike

try this

fun test(){
    handleJson("""{
        "arrivals": [
        {
            "airline": "Iraqi Airways",
            "alia": "Iraqi Airways IAW",
            "flight": "IA136"
        }
        ]
    }""")
}

data class FlightShdu(
        val airline:String,
        val alia:String,
        val flight:String? = null
)
private fun handleJson (jsonString: String?){
    val jsonObj = JSONObject(jsonString)
    val jsonArray = JSONArray(jsonObj.get("arrivals").toString())
    val list =  ArrayList<FlightShdu>()
    var x = 0
    while (x < jsonArray.length()){

        val jsonObject = jsonArray.getJSONObject(x)

        list.add(FlightShdu(

                jsonObject.getString("airline"),
                jsonObject.getString("alia")

        ))
        x++
    }

    list.forEach(::println)
}

Your json starts with { so convert to JSONObject

Where did fn come from?

airline:Iraqi Airways can convert to String

bam bam
  • 371
  • 1
  • 9