I have to work with a server that sends these responses for any request:
For OK:
HTTP 200
{
"jsonrpc": "2.0",
"id": null,
"result": {
"data": {
"exp": 1635637589,
...
...
},
"success": true,
"errors": [],
"messages": []
}
}
For error:
HTTP 200 (yes, and unfortunately that can't be changed)
{
"jsonrpc": "2.0",
"id": null,
"result": {
"data": {},
"success": false,
"errors": [{
"code": 1001,
"message": "Error"
}],
"messages": []
}
}
Notice that data is a json object of a specific type when the response is OK, and a different one when the response is an error. This format is used for all the responses, meaning that data can have different child fields.
I want to use Retrofit + Moshi + RxJava, but I am struggling to find a way to deserialize the response to handle that data field using two different types. I have this model:
data class BaseResponse<T>(
#Json(name = "jsonrpc") val jsonrpc: String,
#Json(name = "id") val id: String?,
#Json(name = "result") val result: BaseResponseResult<T>
)
data class BaseResponseResult<T>(
#Json(name = "data") val data: T, // This is what I have a problem with
#Json(name = "success") val success: Boolean,
#Json(name = "errors") val errors: List<Error>
)
// This would be the data field
data class LoginResponse(
#Json(name = "user_id") val userId: Long,
...
...
...
)
// This would be the data field
data class ProfileResponse(
#Json(name = "name") val name: String,
...
...
...
)
And this would be my Retrofit interface
interface UsersApi {
#POST("api/login")
fun loginReal(#Body request: BaseRequest<LoginRequest>): Single<BaseResponse<LoginResponse>>
#POST("api/profile")
fun loginReal(#Body request: BaseRequest<ProfileRequest>): Single<BaseResponse<ProfileResponse>>
}
I thought about adding a custom deserializer to parse BaseResponse<T> and throw some exception in case the response was an error one, but I am not able to register a deserializer using generics. I have read Moshi's documentation and several posts about deserializers, but I can't get it to work with a generic. Is that possible with Moshi?
I'm using retrofit with Kotlin and coroutines using MVVM pattern. This is the first time I'm using retrofit and kotlin. My issue is I'm calling a news api and getting this error even though I've tried solving my problem on my own but didn't get any proper solution.
Json Response:
{
"status": "ok",
"totalResults": 3923,
-"articles": [
-{
-"source": {
"id": null,
"name": "Finextra"
},
"author": "Editorial Team",
"title": "Solaris Digital Assets wins Bitwala as digital asset custody partner",
"description": "Solaris Digital Assets GmbH, a 100% subsidiary of Solarisbank AG, today announced that it has won Bitwala, Germany’s crypto-banking flagship company, as a partner for its digital asset custody solution.",
"url": "https://www.finextra.com/pressarticle/85033/solaris-digital-assets-wins-bitwala-as-digital-asset-custody-partner",
"urlToImage": "https://www.finextra.com/about/finextra-logo-alt-16-9.jpg",
"publishedAt": "2020-11-17T14:28:00Z",
"content": "Solaris Digital Assets GmbH, a 100% subsidiary of Solarisbank AG, today announced that it has won Bitwala, Germanys crypto-banking flagship company, as a partner for its digital asset custody solutio… [+3321 chars]"
},
-{
-"source": {
"id": null,
"name": "Seeking Alpha"
},
"author": "Ophelia Research",
"title": "Power Corporation Of Canada Is Still A Buy",
"description": "Wealthsimple continues to grow through social media platforms and referral incentives. Power Corporation of Canada continues to grow its investments in start-ups.",
"url": "https://seekingalpha.com/article/4389643-power-corporation-of-canada-is-still-buy",
"urlToImage": "https://static2.seekingalpha.com/uploads/2020/11/15/saupload_EWZQEwLYN4dxnan8QPFcRnpuNy_nvcN-PV5mrbjb97co4v9-QgGK8ZN8UqwxzO3oSPoiDkwnvSMFsyqKGu06-S1TGHHydTAz8VkQXaY5-FjSbTa5-qzCROck4sPk2ZeSD6rYIL1P.png",
"publishedAt": "2020-11-17T14:21:26Z",
"content": "Power Corporation of Canada (OTCPK:PWCDF) is a diversified financial services company that pays out solid dividends due to strong established brands and still has the potential for growth given its i… [+6824 chars]"
}]}
Retrofit Builder:
object RetrofitBuilder {
private const val BASE_URL = "http://newsapi.org/v2/"
private fun getRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build() //Doesn't require the adapter
}
val apiService: ApiService = getRetrofit().create(ApiService::class.java)
}
Api Interface:
interface ApiService {
#GET("sources/apikey")
suspend fun getTopHeadlines(): Model
}
Api Helper:
suspend fun getTopHeadlines() = apiService.getTopHeadlines()
Main Repository:
suspend fun getTopHeadlines() = apiHelper.getTopHeadlines()
ViewModelFactory:
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
return MainViewModel(MainRepository(apiHelper)) as T
}
throw IllegalArgumentException("Unknown class name")
}
MainViewModel:
fun getTopHeadlines() = liveData(Dispatchers.IO) {
emit(Resource.loading(data = null))
try {
emit(Resource.success(data = mainRepository.getTopHeadlines()))
} catch (exception: Exception) {
emit(Resource.error(data = null, msg = exception.message ?: "Error Occurred!"))
}
}
Model Class:
data class Model(val status: String,val totalResults: Int,val articles: List<Article>)
Article Class:
data class Article(
val source: Source,
val author: String,
val content: String,
val description: String,
val publishedAt: String,
val title: String,
val url: String,
val urlToImage: String
)
Source Class:
data class Source(
val id: Any,
val name: String
)
Main Activity:
viewModel.getTopHeadlines().observe(this, Observer {
it?.let { resource ->
when (resource.status) {
Status.SUCCESS -> {
Log.e("MainClass","Data caught: "+it.message);
// resource.data?.let { users -> retrieveList(users) }
}
Status.ERROR -> {
Log.e("MainClass","Exception caught: "+it.message);
Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
}
Status.LOADING -> {
}
}
}
})
Alright. Judging by this documentation and by your code, there are plenty things wrong here, so I will go into more detail below.
Your Model class that you created:
Here is the POJO structure that I generated for the Json you provided..
Something like this:
data class Base(
#SerializedName("status") val status: String,
#SerializedName("totalResults") val totalResults: Int,
#SerializedName("articles") val articles: List<Articles>
)
data class Articles(
#SerializedName("source") val source: Source,
#SerializedName("author") val author: String,
#SerializedName("title") val title: String,
#SerializedName("description") val description: String,
#SerializedName("url") val url: String,
#SerializedName("urlToImage") val urlToImage: String,
#SerializedName("publishedAt") val publishedAt: String,
#SerializedName("content") val content: String
)
data class Source(
#SerializedName("id") val id: String,
#SerializedName("name") val name: String
)
Model class is done. Moving on to your Retrofit code.
Your Retrofit instance:
#GET(sources/apikey) line is completely wrong. Nothing like that exists in documentation and you won't be able to get anything out of it. In order to get what you need, you need to reference top-headlines or sources or everything.
Your object RetrofitBuilder can be simplified in some ways.
You need to query ApiKey together with your request which you are not doing
You need to query Country together with your request which you are not doing as well
Lets apply the changes then. (I am using top-headlines here since it fits our model class):
// This is much simplified version of what you have written.
interface NewsApi {
// Here we use correct API endpoint.
#GET("top-headlines")
suspend fun getTopHeadlines(
// This is how you Query necessary parameters for APIs
// In our case, we need to query Country + apiKey
#Query("country") country: String = "us",
#Query("apiKey") apiKey: String = "%InsertYourApiKey%"
): Response<Base> // Response<Base> is simply a class that allows you to read API's response codes, body and other details that you might need for processing response information.
companion object {
fun getInstance(): NewsApi {
return Retrofit.Builder()
.baseUrl("http://newsapi.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(NewsApi::class.java) // Creation doesn't have to be separate, you can have it in here for more concise code.
}
}
}
After these changes, all you have to do:
Insert your API key into interface where I have written %InsertYourApiKey
Use the following code anywhere you need:
...
val newsApi = NewsApi.getInstance()
val response = newsApi.getTopHeadlines()
// Do whatever you need with your response.
I am new in Android development, and I am trying to get data from server. the general JSON response structure will be like this
{
"success": "1",
"data": [
{
"customers_id": 4,
"customers_gender": "0",
"customers_firstname": "TES IOS",
"customers_lastname": "TES IOS",
"customers_dob": "2018-12-27",
"email": "TES002#email.com",
"user_name": "TES002",
"customers_default_address_id": 0,
"customers_telephone
},
"message": "Successfully get user data from server"
}
the "success" and "message" field will be the same (will always be string). but the "data" can be different for other request call. It can send user data, store data or product data, or even Array/List of Products.
so I want to make general reusable class to catch that JSON response. the class will be like this, I set the "data" to be Any, and then later it will be casted back to User object:
class ServerData(successStatus: Int, data: Any, message: String) {
val isSuccessfull : Boolean
val data : Any
val message : String
init {
isSuccessfull = successStatus != 0
this.data = data
this.message = message
}
}
the interface is like this:
interface LakuinAPI {
#FormUrlEncoded
#POST("processlogin")
fun performLogin(
#Field("kode_customer") outletCode: String,
#Field("password") password: String
): Call<ServerData>
}
and then I use it in the activity, like the code below:
private fun sendLoginDataToServer(outletCode: String, password: String) {
val call = lakuinAPI.performLogin(outletCode,password)
call.enqueue(object: Callback<ServerData> {
override fun onFailure(call: Call<ServerData>, t: Throwable) {
Toast.makeText(this#LoginActivity,t.localizedMessage,Toast.LENGTH_LONG).show()
}
override fun onResponse(call: Call<ServerData>, response: Response<ServerData>) {
if (!response.isSuccessful) {
Toast.makeText(this#LoginActivity,"Code: " + response.code(),Toast.LENGTH_LONG).show()
return
}
val lakuinServerData = response.body()
val userList = lakuinServerData?.data as List<User> // the error in here
val userData = userList.first() // the error in here
println(userData)
}
})
}
but I get error message:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap
cannot be cast to com.ssss.lakuinkotlin.Model.User
I give comment in the code above the location of the error. I don't why it happened.
to be honest, I am not if this is the correct way to catch user data from general response JSON like the the JSON above. is there a better way ?
You can use generics to achieve it
class Response<Data> constructor() : ResponseSimple() {
#SerializedName(FIELD_DATA)
var data: Data? = null
private constructor(data: Data) : this() {
this.data = data
}
companion object {
const val FIELD_SUCCESS = "success"
const val FIELD_ERROR = "error"
const val FIELD_DATA = "data"
const val FIELD_MESSAGE = "message"
#JvmStatic
fun <Data> create(data: Data): Response<Data> {
return Response(data)
}
}
}
And ResponseSimple is
open class ResponseSimple {
#SerializedName(Response.FIELD_ERROR)
var error: String = ""
#SerializedName(Response.FIELD_SUCCESS)
var succes: Boolean = false
#SerializedName(Response.FIELD_MESSAGE)
var message:String = ""
}
Then api response should be Call<Response<ServerData>>.
And about ClassCastException, you can't convert ServerData to User just using as.
You need to use Call<Response<ArrayList<User>>> or create class converter.
Try replacing this line :
val userList = lakuinServerData?.data as List<User>
with:
val userList = lakuinServerData?.data as new TypeToken<List<User>>(){}.getType()
I'm receiving a quite deep JSON object string from a service which I must parse to a JSON object and then map it to classes.
How can I transform a JSON string to object in Kotlin?
After that the mapping to the respective classes, I was using StdDeserializer from Jackson. The problem arises at the moment the object had properties that also had to be deserialized into classes. I was not able to get the object mapper, at least I didn't know how, inside another deserializer.
Preferably, natively, I'm trying to reduce the number of dependencies I need so if the answer is only for JSON manipulation and parsing it'd be enough.
There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released
https://github.com/Kotlin/kotlinx.serialization
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON
#Serializable
data class MyModel(val a: Int, #Optional val b: String = "42")
fun main(args: Array<String>) {
// serializing objects
val jsonData = JSON.stringify(MyModel.serializer(), MyModel(42))
println(jsonData) // {"a": 42, "b": "42"}
// serializing lists
val jsonList = JSON.stringify(MyModel.serializer().list, listOf(MyModel(42)))
println(jsonList) // [{"a": 42, "b": "42"}]
// parsing data back
val obj = JSON.parse(MyModel.serializer(), """{"a":42}""")
println(obj) // MyModel(a=42, b="42")
}
You can use this library https://github.com/cbeust/klaxon
Klaxon is a lightweight library to parse JSON in Kotlin.
Without external library (on Android)
To parse this:
val jsonString = """
{
"type":"Foo",
"data":[
{
"id":1,
"title":"Hello"
},
{
"id":2,
"title":"World"
}
]
}
"""
Use these classes:
import org.json.JSONObject
class Response(json: String) : JSONObject(json) {
val type: String? = this.optString("type")
val data = this.optJSONArray("data")
?.let { 0.until(it.length()).map { i -> it.optJSONObject(i) } } // returns an array of JSONObject
?.map { Foo(it.toString()) } // transforms each JSONObject of the array into Foo
}
class Foo(json: String) : JSONObject(json) {
val id = this.optInt("id")
val title: String? = this.optString("title")
}
Usage:
val foos = Response(jsonString)
You can use Gson .
Example
Step 1
Add compile
compile 'com.google.code.gson:gson:2.8.2'
Step 2
Convert json to Kotlin Bean(use JsonToKotlinClass)
Like this
Json data
{
"timestamp": "2018-02-13 15:45:45",
"code": "OK",
"message": "user info",
"path": "/user/info",
"data": {
"userId": 8,
"avatar": "/uploads/image/20180115/1516009286213053126.jpeg",
"nickname": "",
"gender": 0,
"birthday": 1525968000000,
"age": 0,
"province": "",
"city": "",
"district": "",
"workStatus": "Student",
"userType": 0
},
"errorDetail": null
}
Kotlin Bean
class MineUserEntity {
data class MineUserInfo(
val timestamp: String,
val code: String,
val message: String,
val path: String,
val data: Data,
val errorDetail: Any
)
data class Data(
val userId: Int,
val avatar: String,
val nickname: String,
val gender: Int,
val birthday: Long,
val age: Int,
val province: String,
val city: String,
val district: String,
val workStatus: String,
val userType: Int
)
}
Step 3
Use Gson
var gson = Gson()
var mMineUserEntity = gson?.fromJson(response, MineUserEntity.MineUserInfo::class.java)
Not sure if this is what you need but this is how I did it.
Using import org.json.JSONObject :
val jsonObj = JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1))
val foodJson = jsonObj.getJSONArray("Foods")
for (i in 0..foodJson!!.length() - 1) {
val categories = FoodCategoryObject()
val name = foodJson.getJSONObject(i).getString("FoodName")
categories.name = name
}
Here's a sample of the json :
{"Foods": [{"FoodName": "Apples","Weight": "110" } ]}
I personally use the Jackson module for Kotlin that you can find here: jackson-module-kotlin.
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:$version"
As an example, here is the code to parse the JSON of the Path of Exile skilltree which is quite heavy (84k lines when formatted) :
Kotlin code:
package util
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.*
import java.io.File
data class SkillTreeData( val characterData: Map<String, CharacterData>, val groups: Map<String, Group>, val root: Root,
val nodes: List<Node>, val extraImages: Map<String, ExtraImage>, val min_x: Double,
val min_y: Double, val max_x: Double, val max_y: Double,
val assets: Map<String, Map<String, String>>, val constants: Constants, val imageRoot: String,
val skillSprites: SkillSprites, val imageZoomLevels: List<Int> )
data class CharacterData( val base_str: Int, val base_dex: Int, val base_int: Int )
data class Group( val x: Double, val y: Double, val oo: Map<String, Boolean>?, val n: List<Int> )
data class Root( val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )
data class Node( val id: Int, val icon: String, val ks: Boolean, val not: Boolean, val dn: String, val m: Boolean,
val isJewelSocket: Boolean, val isMultipleChoice: Boolean, val isMultipleChoiceOption: Boolean,
val passivePointsGranted: Int, val flavourText: List<String>?, val ascendancyName: String?,
val isAscendancyStart: Boolean?, val reminderText: List<String>?, val spc: List<Int>, val sd: List<String>,
val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )
data class ExtraImage( val x: Double, val y: Double, val image: String )
data class Constants( val classes: Map<String, Int>, val characterAttributes: Map<String, Int>,
val PSSCentreInnerRadius: Int )
data class SubSpriteCoords( val x: Int, val y: Int, val w: Int, val h: Int )
data class Sprite( val filename: String, val coords: Map<String, SubSpriteCoords> )
data class SkillSprites( val normalActive: List<Sprite>, val notableActive: List<Sprite>,
val keystoneActive: List<Sprite>, val normalInactive: List<Sprite>,
val notableInactive: List<Sprite>, val keystoneInactive: List<Sprite>,
val mastery: List<Sprite> )
private fun convert( jsonFile: File ) {
val mapper = jacksonObjectMapper()
mapper.configure( DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true )
val skillTreeData = mapper.readValue<SkillTreeData>( jsonFile )
println("Conversion finished !")
}
fun main( args : Array<String> ) {
val jsonFile: File = File( """rawSkilltree.json""" )
convert( jsonFile )
JSON (not-formatted): http://filebin.ca/3B3reNQf3KXJ/rawSkilltree.json
Given your description, I believe it matches your needs.
GSON is a good choice for Android and Web platform to parse JSON in a Kotlin project. This library is developed by Google.
https://github.com/google/gson
1. First, add GSON to your project:
dependencies {
implementation 'com.google.code.gson:gson:2.8.9'
}
2. Now you need to convert your JSON to Kotlin Data class:
Copy your JSON and go to this(https://json2kt.com) website and paste your JSON to Input Json box. Write package(ex: com.example.appName) and Class name(ex: UserData) in proper box. This site will show live preview of your data class below and also you can download all classes at once in a zip file.
After downloading all classes extract the zip file & place them into your project.
3. Now Parse like below:
val myJson = """
{
"user_name": "john123",
"email": "john#example.com",
"name": "John Doe"
}
""".trimIndent()
val gson = Gson()
var mUser = gson.fromJson(myJson, UserData::class.java)
println(mUser.userName)
Done :)
This uses kotlinx.serialization like Elisha's answer. Meanwhile the project is past version 1.0 so the API has changed. Note that e.g. JSON.parse was renamed to Json.decodeFromString. Also it is imported in gradle differently starting in Kotlin 1.4.0:
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.0"
}
apply plugin: 'kotlinx-serialization'
Example usage:
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
#Serializable
data class Point(val x: Int, val y: Int)
val pt = Json.decodeFromString<Point>("""{"y": 1, "x": 2}""")
val str = Json.encodeToString(pt) // type can be inferred!
val ilist = Json.decodeFromString<List<Int>>("[-1, -2]")
val ptlist = Json.decodeFromString<List<Point>>(
"""[{"x": 3, "y": 4}, {"x": 5, "y": 6}]"""
)
You can use nullable types (T?) for both nullable and optional fields:
#Serializable
data class Point2(val x: Int, val y: Int? = null)
val nlist = Json.decodeFromString<List<Point2>>(
"""[{"x": 7}, {"x": 8, "y": null}, {"x": 9, "y": 0}]"""
)
Kotlin's data class is a class that mainly holds data and has members, .toString() and other methods (e.g. destructuring declarations) automatically defined.
To convert JSON to Kotlin use http://www.json2kotlin.com/
Also you can use Android Studio plugin. File > Settings, select Plugins in left tree, press "Browse repositories...", search "JsonToKotlinClass", select it and click green button "Install".
After AS restart you can use it. You can create a class with File > New > JSON To Kotlin Class (JsonToKotlinClass). Another way is to press Alt + K.
Then you will see a dialog to paste JSON.
In 2018 I had to add package com.my.package_name at the beginning of a class.
First of all.
You can use JSON to Kotlin Data class converter plugin in Android Studio for JSON mapping to POJO classes (kotlin data class).
This plugin will annotate your Kotlin data class according to JSON.
Then you can use GSON converter to convert JSON to Kotlin.
Follow this Complete tutorial:
Kotlin Android JSON Parsing Tutorial
If you want to parse json manually.
val **sampleJson** = """
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio
reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita"
}]
"""
Code to Parse above JSON Array and its object at index 0.
var jsonArray = JSONArray(sampleJson)
for (jsonIndex in 0..(jsonArray.length() - 1)) {
Log.d("JSON", jsonArray.getJSONObject(jsonIndex).getString("title"))
}
Kotlin Serialization
Kotlin specific library by JetBrains for all supported platforms – Android, JVM, JavaScript, Native.
https://github.com/Kotlin/kotlinx.serialization
Moshi
Moshi is a JSON library for Android and Java by Square.
https://github.com/square/moshi
Jackson
https://github.com/FasterXML/jackson
Gson
Most popular but almost deprecated.
https://github.com/google/gson
JSON to Java
http://www.jsonschema2pojo.org/
JSON to Kotlin
IntelliJ plugin - https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-
Parse JSON string to Kotlin object
As others recommend, Gson library is the simplest way!
If the File is in the Asset folder you can do like this, first add
dependencies {
implementation 'com.google.code.gson:gson:2.9.0'
}
then get a file from Asset:
jsonString = context.assets.open(fileName).bufferedReader().use { it.readText() }
then use Gson :
val gson = Gson()
val listPersonType = object : TypeToken<List<Person>>() {}.type
var persons: List<Person> = gson.fromJson(jsonFileString, listPersonType)
persons.forEachIndexed { idx, person -> Log.i("data", "> Item $idx:\n$person") }
Where Person is a Model/Data class, like this
data class Person(val name: String, val age: Int, val messages: List) {
}
If you prefer parsing JSON to JavaScript-like constructs making use of Kotlin syntax, I recommend JSONKraken, of which I am the author.
You can do things like:
val json: JsonValue = JsonKraken.deserialize("""{"getting":{"started":"Hello World"}}""")
println(JsonKraken.serialize(json)) //prints: {"getting":{"started":"Hello World"}}
println(json["getting"]["started"].cast<String>()) //prints: Hello World
Suggestions and opinions on the matter are much apreciated!
I created a simple Extention function to convert JSON string to model class
inline fun <reified T: Any> String.toKotlinObject(): T =
Gson().fromJson(this, T::class.java)
Usage method
stringJson.toKotlinObject<MyModelClass>()
http://www.jsonschema2pojo.org/
Hi you can use this website to convert json to pojo.
control+Alt+shift+k
After that you can manualy convert that model class to kotlin model class. with the help of above shortcut.
Seems like Kotlin does not have any built-in method as in many cases it just imports and implements some tools from Java. After trying lots of packages, finally this one worked reasonably. This fastjson from alibaba, which is very easy to use. Inside build gradle dependencies:
implementation 'com.alibaba:fastjson:1.1.67.android'
Inside your Kotlin code:
import com.alibaba.fastjson.JSON
var jsonDecodedMap: Map<String, String> =
JSON.parse(yourStringValueHere) as Map<String, String>;
Download the source of deme from here(Json parsing in android kotlin)
Add this dependency:
compile 'com.squareup.okhttp3:okhttp:3.8.1'
Call api function:
fun run(url: String) {
dialog.show()
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
dialog.dismiss()
}
override fun onResponse(call: Call, response: Response) {
var str_response = response.body()!!.string()
val json_contact:JSONObject = JSONObject(str_response)
var jsonarray_contacts:JSONArray= json_contact.getJSONArray("contacts")
var i:Int = 0
var size:Int = jsonarray_contacts.length()
al_details= ArrayList();
for (i in 0.. size-1) {
var json_objectdetail:JSONObject=jsonarray_contacts.getJSONObject(i)
var model:Model= Model();
model.id=json_objectdetail.getString("id")
model.name=json_objectdetail.getString("name")
model.email=json_objectdetail.getString("email")
model.address=json_objectdetail.getString("address")
model.gender=json_objectdetail.getString("gender")
al_details.add(model)
}
runOnUiThread {
//stuff that updates ui
val obj_adapter : CustomAdapter
obj_adapter = CustomAdapter(applicationContext,al_details)
lv_details.adapter=obj_adapter
}
dialog.dismiss()
}
})