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 am trying to serialize the content of a json string that can take the following format:
-723232569: {
"lat": 8.2,
"lon": -90.3,
"schedule": {
"friday": [
{
"date_arr": "friday",
"remarks": " OK",
"time_arr": "07:10",
"time_dep": "06:40",
"trans_name": "C"
}
]
}
However I am struggling with my current serializable class implementation. The top key (-723232569) will vary, it will be generated randomly from one iteration to another. I would like to extract they key and its value with the following class implementation.
#Serializable
data class TimeSlot(val date_arr: String,
val remarks: String,
val time_arr: String,
val time_dep: String,
val trans_link: String,
val trans_name: String,
val trans_tel: String,
val to_lat: String? = null,
val to_lon: String? = null)
#Serializable
data class Schedule(val monday: List<TimeSlot>,
val tuesday: List<TimeSlot>,
val wednesday: List<TimeSlot>,
val thursday: List<TimeSlot>,
val friday: List<TimeSlot>,
val saturday: List<TimeSlot>,
val sunday: List<TimeSlot>)
#Serializable
data class Stop(val lat: Double,
val lon: Double,
val schedule: Schedule)
However when executing the following code I am encountering
try {
val neww = """-723232569: {
"lat": 8.2,
"lon": -90.3,
"schedule": {
"friday": [
{
"date_arr": "friday",
"remarks": " OK",
"time_arr": "07:10",
"time_dep": "06:40",
"trans_name": "C"
}
]
}"""
val res = format.decodeFromString<Stop>(neww)
} catch (ioException: IOException) {
ioException.printStackTrace()
}
Unexpected JSON token at offset 27: Encountered an unknown key '-723232569'.
Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys.
I have project with android app that fetch post from wordpress rest api
some field that i take is like this list.
[
{
"id": 43600,
"date": "2020-09-07T19:52:47",
"title": {
"rendered": "Video: .... "
},
"content": {
"rendered": "<div class=\"wp-block-embed__wrapper\"></div>",
"protected": false
},
"author": 31,
"featured_media": 43601,
"categories": [
788,
2760
]
}
]
Already read :
https://developer.android.com/training/data-storage/room
How to parse data of WordPress REST API using Retrofit and GSON?
Wordpress API - How to loop through a JSON Array of objects in Android/Java
Android Kotlin parsing nested JSON
Parse Json to Primative Array Kotlin
the closest answer but mostly in converter
Android Room Database: How to handle Arraylist in an Entity?
https://medium.com/#gilesjeremydev/room-through-a-complete-example-ce5c9ed417ba
I tried to save it into local storage with room in single entity. But based on google doc, it would seperate into 2 entities tied with annotation #relation
#Entity(tableName = "post")
data class SomePost(
#PrimaryKey
#field:SerializedName("id")
val id: Int,
#field:SerializedName("date")
val date: String,
#Embedded
#field:SerializedName("title")
val title: PostTitle,
#Embedded
#field:SerializedName("content")
val content: PostContent,
#field:SerializedName("featured_media")
val imageId: Int,
#field:SerializedName("author")
val author: Int
)
#Entity
data class PostCategories(
#PrimaryKey(autoGenerate = true)
val id: Int,
#field:SerializedName("categories")
val postCategories: Int
)
data class SomePostRelationship (
#Embedded
var post: SomePost? = null,
#Relation(
parentColumn = "id",
entityColumn = "categories"
)
var categories: List<PostCategories>? = null
)
interface PostService {
companion object {
const val ENDPOINT = "https://example.com/wp-json/"
}
// Posts
#GET("wp/v2/posts/")
suspend fun getPostAll(
#Query("page") page: Int? = null,
#Query("per_page") perPage: Int? = null,
#Query("search") search: String? = null,
#Query("order") order: String? = null
): Response<List<somePost>>
The problem is data class PostCategories.
My question is how to serialization json array into entity data class of categories for android room.
if there already answer or same question hope can link to it.
After tried some variation.
I decided to used converter and combine it in on dataclass for now.
#Entity(tableName = "post")
data class SomePost(
...
#field:SerializedName("categories")
var categories: ArrayList<Int>? = null,
...
)
class Converters {
...
#TypeConverter
fun listToInt(value: ArrayList<Int>?): String? {
return Gson().toJson(value)
}
#TypeConverter
fun intToList(value: String?): ArrayList<Int>? {
val type = object : TypeToken<ArrayList<Int>?>() {}.type
return Gson().fromJson(value, type)
}
}
This is what my json looks like
{
"sub": "9",
"auth_time": 1559381757,
"idp": "idsrv",
"role": [
"Employer",
"Employee",
"Student"
],
"iss": "",
"aud": "",
"exp": 1574933757,
"nbf": 1559381757
}
This is the object I want to convert this Json into.
data class Claims (
#SerializedName("nameid") val nameId: String,
#SerializedName("unique_id") val uniqueId: String,
#SerializedName("sub") val sub: String,
#SerializedName("unifiedNumber") val unifiedNumber: String,
#SerializedName("role") var roleList: List<Role>
)
I wrote a custom Deserializer (which works in Java) for the List type
class RoleDeserializer : JsonDeserializer<List<Role>> {
private var roleId = 0
#Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): MutableList<Role> {
val resultList = ArrayList<Role>()
if (json.isJsonArray) {
for (e in json.asJsonArray) {
resultList.add(Role(id = roleId++, name = e.asString))
}
} else if (json.isJsonObject) {
resultList.add(Role(id = roleId++, name = json.asString))
} else if (json.isJsonPrimitive) {
if ((json as JsonPrimitive).isString)
resultList.add(Role(id = roleId++, name = json.getAsString()))
} else {
throw RuntimeException("Unexpected JSON type: " + json.javaClass)
}
return resultList
}
}
This is how I register my type adapter
val listType: Type = object : TypeToken<List<Role>>() {}.type
val gson = GsonBuilder().registerTypeAdapter(listType, RoleDeserializer()).create()
val claims = gson.fromJson(stringJson, Claims::class.java)
I still get a parse exception stating that
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 161 path $.role[0]
and my RoleDeserializer is never called. Am I doing something wrong while registering the type adapter?
Try to replace
val listType: Type = object : TypeToken<List<Role>>() {}.type
with
val listType: Type = object : TypeToken<MutableList<Role>>() {}.type
The role is String array in JSON
Use this
#SerializedName("role") var roleList: List<String>
Instead of this
#SerializedName("role") var roleList: List<Role>
Try this
data class Claims (
#SerializedName("nameid") val nameId: String,
#SerializedName("unique_id") val uniqueId: String,
#SerializedName("sub") val sub: String,
#SerializedName("unifiedNumber") val unifiedNumber: String,
#SerializedName("role") var roleList: List<String>
)
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()
}
})