How to parse a data class into JSON string for Kotlin? - android

I wonder what is the way to convert a Kotlin data class into its equivalent json string. Json keys should be configurable.
Let's say I have a class,
data class Student(name: String?, roll: Int?, mark: Int?) {
}
I want to make a Json from this Student object where keys will be,
stundent_name, stundent_roll, stundent_mark
Moreover, I may also need to make a json from list of student with key students. How can I do so? I know using Gson I can create object from json string. How to do the reverse?

data class Student(
#SerializedName("stundent_name")
val name: String?,
#SerializedName("stundent_roll")
val roll: Int?,
#SerializedName("stundent_mark")
val mark: Int?
)
And the code for convertion is:
val gson = Gson()
val student = Student("John", 1, 5)
gson.toJson(student)
This code makes String like this:
{"stundent_mark":5,"stundent_name":"John","stundent_roll":1}
And if you need to create JsonArray, just do the same with your List of students:
gson.toJson(list)

Related

Android: How to parse nested json array with different data type objects using retrofit - moshi?

I want to parse nested json using retrofit moshi. The json data i'm having is an array, inside array first element is string & second is again an array.
I don't want to parse first element in the array ("list"), just want to parse second element from the array (i.e. Inner array).
But i'm facing challenges exactly here with the data object to be use.
Obviously we can use Any type in kotlin with list, but again will loose type of the object inside the list.
Json Format:
{
"results": [
"list",
[
{
//jsonobj
},
{
//jsonobj
}
]
]
}
I want to parse json with this Data class that i have created without parsing first element & parse directly second element.
#JsonClass(generateAdapter = true)
data class ResponseModel(
#Json(name = "results")
val results: List<Results?>?,
) {
#JsonClass(generateAdapter = true)
data class Results(
#Json(name = "reference")
val reference: String?,
#Json(name = "enabled")
val enabled: Boolean,
)
}
fromJson overridden function
#Throws(IOException::class)
override fun fromJson(reader: JsonReader): C {
val result = newCollection()
reader.beginArray()
while (reader.hasNext()) {
result?.add(elementAdapter.fromJson(reader)!!)
}
reader.endArray()
return result
}
This is throwing an exception saying EXPECTED_OBJECT but it was STRING when trying to parse first element ("list").
i'm stuck here & not able to proceed further.
So can somebody plz help me to get out from here? any help will be appreciated.

Android Kotlin Room Type Converter for JSON Array

I know there's a lot of other post regarding type converter, but I am facing a different scenario here.
What's different is actually the Json format that I am receiving from my server, and I cant ask them to update their format just so I can fix this issue.
I know Im just missing something or just doing it wrong
Here's my sample Json format
[{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}]
The cars format is not object, but JSON Array, and I kinda want to store it under List format in Kotlin
#Entity(tableName = "person")
data class Person(
#PrimaryKey
var name: String,
var age: Int,
#SerializedName("cars")
#TypeConverters(ListTypeConverter::class)
var cars: Array<Car>
)
Any help will be appreciated.
Thanks all
Your POJO it not correct, check below one
#Entity(tableName = "person")
data class Person(
#PrimaryKey
var name: String,
var age: Int,
#SerializedName("cars")
#TypeConverters(ListTypeConverter::class)
var cars: Array<String>
)
cars is a list of String, not Object
Use
var cars = mutableListOf<String>()
then add JSONArray data inside it

How can I deserialize this?

I have a JSON response of an API REST call that I am not pretty sure how should I deserialize...
{
.....
"date": "10-10-19",
"rates": {
"GBP" : 101.01,
"EUR" : 102.01,
"AUD" : 103.4,
......
}
}
I would like to know How could I deserialize the "rates" object?. I think it was a Map object so using Gson I make the next POJO:
class POJO(
private val base: String,
private val date: Date,
private val rates: Rate
)
And my Rate class is
class Rate ( private val currency : Map <String, Double> )
It doesn't make any problem unless I try to use this Map in my class. When I try to access to this variable for example here :
view?.converterBinder!!.setCurrencyList(it.data!!.rates.currency)
currency is null because I think Gson doesn't know how to resolve it. I don't know if I had to deserialize it manually or there are any solution for this using Gson.
Any thoughts??
The provided Json is completely wrong, this is how it should be formatted
{
"date": "10-10-19",
"rates": {
"GBP": 101.01,
"EUR": 102.01
}
}
Please check with https://jsonlint.com to confirm the validity of a Json.
So you have a json object with a String "date", then you have another json object called "rates" containing 2 numeric Doubles "GBP" and "EUR".
Each Json should be represented by a class, so to parse it create the following object containing the 2 classes
object Models {
data class Rates(#SerializedName("GBP") val gbp: Double,
#SerializedName("EUR") val eur: Double)
data class ExchangeRates(#SerializedName("date") val date: String,
#SerializedName("rates") val rates: Rates)
}
Now you pass the class ExchangeRates to Gson to deserialize your object and you should have all the data in place.

retrofit generate unformatted complex json object

I am having a very strange problem
I am trying to build a complex json object which contains nested json
I have created it but when I send the request it crash
here is the format that I need
{"JR":"{"Text":"","userID":4,"Context":"","ClinicId":1}","TO":"getWatsonMessage","ver":2}
what I found in the request body as following:
{"JR":"{\"Text\":\"\",\"userID\":4,\"Context\":\"\",\"ClinicId\":1}","TO":"getWatsonMessage","ver":2}
which make the app crash
here is my code
data class MyBody #JvmOverloads constructor(
#SerializedName("ver") val version: Int,
#SerializedName("TO") val methodName: String,
#SerializedName("JR") val jsonParams: String,
#SerializedName("Method") var methodType: String? = null
)
and this is how I create the sub json object
val jsonJR = JSONObject()
jsonJR.put("Text",text)
jsonJR.put("userID",userId)
jsonJR.put("Context",context)
jsonJR.put("ClinicId",clinicId)
can anyone please help ?
It seems like the problem is with your JR of type String.
All the other params are in the proper format right?
So, I suggest that you provide type JR to another custom data class like
data class JRDataClass{
Text : String,
//and the rest of the data types
}

how to parse custom json array list in kotlin using GSON

this is my data class, need to parse the arraylist of type link
class DetailResponse {
data class BasicInfo (
#SerializedName("favorite") val isFavorite: Boolean,
#SerializedName("screenshots") val screenshots: ArrayList<Link>
)
data class Link (
#SerializedName("href") val href: String
)
}
What you have done is correct. Now you just have to use Gson to convert this JSON to object
val gson = Gson()
val detailResponse = gson.fromJson(resp,DetailedResponse::class.java)
where "resp" is your json string.

Categories

Resources