Reputation: 1180
I got this error when I am trying to get json array from JSONObject ArrivedResult
.
Here is my json :
{
"ArrivedResult": {
"arrivals": [
{
"ident": "MSR637",
"aircrafttype": "A321",
"actualdeparturetime": 1541399820,
"actualarrivaltime": 1541406652,
"origin": "HECA"
}
]
}
}
my code is
private fun handleJson(jsonString: String?) {
val jsonObj = JSONObject(jsonString)
val ArrivedResult = jsonObj.getJSONObject("ArrivedResult")
val jsonArray = JSONArray(ArrivedResult.get("arrivals").toString())
val list = ArrayList<FlightShdu>()
var x = 0
while (x < jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(x)
list.add(FlightShdu(
jsonObject.getString("aircrafttype"),
jsonObject.getString("destination")
))
x++
}
}
The error I got is Caused by: org.json.JSONException: No value for ArrivedResult
Upvotes: 2
Views: 226
Reputation: 2931
I'm not sure what library you're using to deserialize JSON, but if you have fallback to using another ones than it's pretty easy. Foe example with Klaxon:
// To parse the JSON, install Klaxon and do:
//
// val root = Root.fromJson(jsonString)
import com.beust.klaxon.*
private val klaxon = Klaxon()
data class Root (
@Json(name = "ArrivedResult")
val arrivedResult: ArrivedResult
) {
public fun toJson() = klaxon.toJsonString(this)
companion object {
public fun fromJson(json: String) = klaxon.parse<Root>(json)
}
}
data class ArrivedResult (
val arrivals: List<Arrival>
)
data class Arrival (
val ident: String,
val aircrafttype: String,
val actualdeparturetime: Long,
val actualarrivaltime: Long,
val origin: String
)
Or with kotlinx.serialization
// To parse the JSON, install kotlin's serialization plugin and do:
//
// val json = Json(JsonConfiguration.Stable)
// val root = json.parse(Root.serializer(), jsonString)
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.internal.*
@Serializable
data class Root (
@SerialName("ArrivedResult")
val arrivedResult: ArrivedResult
)
@Serializable
data class ArrivedResult (
val arrivals: List<Arrival>
)
@Serializable
data class Arrival (
val ident: String,
val aircrafttype: String,
val actualdeparturetime: Long,
val actualarrivaltime: Long,
val origin: String
)
Please note that in both cases I have top-leve Root
class, which is needed to unwrap top-level {}
object from your example
Upvotes: 2