I have used Anko to get a JSON in Kotlin and it works well but I do not know how can I access to each value.
I have this code which prints out the whole JSON:
doAsync {
val result = URL("url.json").readText()
uiThread {
longToast(result)
}
}
So now that I have the whole JSON, how can I access to each field?
I have tried with result[0].toString()
and result.get(0).toString()
but it did not work because it prints out the first character of result
which is [
Use JSONArray
and JSONObject
to parse json like below.
In Java:
JSONArray jsonArray = new JSONArray(result);
for (int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String user = jsonObject.getString("user");
String password = jsonObject.getString("password");
}
In Kotlin:
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val user = jsonObject.getString("user")
val password = jsonObject.getString("password")
}