简体   繁体   中英

How to parse a JSON in Kotlin (Anko)?

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")
}

There is a cool kotlinx library called Kotlinx.Serialization

In root build.gradle

buildScript {
    ...
    classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}

The use the @Serializable annotation ( for your custom class )

For deserialization use:-

 Json.parse(YourClass.serializer() ,resultJson) // this will deserialize

For serialization use:-

 Json.stringify(YourClass.serializer(), yourClassObj) // this will give string value of the json

For more info check this .

You can use Google's Gson library to parse Json. You can follow the link on how to add it to your project.

data class UserCredential(val email:String, val password:String)

then you can access fields in your json this way

doAsync {
  val result = URL("url.json").readText()

  val userCredentialList = Gson().fromJson<List<UserCredential>>(result, object :TypeToken<List<UserCredential>>(){}.type)
     uiThread {
     longToast(result)
  }
}

then you can access fields in json by using

userCredentialList[0].email

You can use this library https://github.com/cbeust/klaxon

Klaxon is a lightweight library to parse JSON in Kotlin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM