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
}
Related
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.
I have this model that I would like to parse from JSON:
class CFInsertedValuesStructure {
#SerializedName("id")
val id : Int? = null
#SerializedName("value")
val value : List<String> = listOf();
#SerializedName("field_id")
val field_id : String? = null
}
There is a problem with the parameter "value" because it isn't always an array of String, sometimes it could be just a String type.
So when happens I would like to recognise it and create an array of just one String.
depending on what library you use the json parsing it may require a custom parsing type e.g. for kotlinx.serialization you might need to do something like a custom serializer
https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#specifying-serializer-on-a-property
better still : tell you server-side developer it should always be an 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
I'm really new in programming, and recently started a project in Kotlin with Android Studio.
So, I have a problem with a JSON object. I get data from an BroadcastReceiver object, a String to be more specific, with the next format:
{"s1":1}
This, is a simple string. So I took in a function call toJson and I do this.
private fun toJson(data:String): JSONObject {
var newData: String = data.replace("\"","")
newData = newData.replace("{","")
newData = newData.replace("}","")
val newObject = newData.split(":")
val name = newObject[0]
val value = newObject[1]
val rootObject = JSONObject()
rootObject.put(name,value)
return rootObject
}
Im doing this the right way?, how can I improve my code?
Thanks for your help, and sorry for my english!
Welcome to StackOverflow!
In 2019 no-one is really parsing JSON manually. It's much easier to use Gson library. It takes as an input your object and spits out JSON string and vice-versa.
Example:
data class MyClass(#SerializedName("s1") val s1: Int)
val myClass: MyClass = Gson().fromJson(data, MyClass::class.java)
val outputJson: String = Gson().toJson(myClass)
This way you're not working with JSON string directly but rather with Kotlin object which is type-safe and more convenient.
Look at the docs. It's pretty big and easy to understand
Here is some tutorials:
https://www.youtube.com/watch?v=f-kcvxYZrB4
http://www.studytrails.com/java/json/java-google-json-introduction/
https://www.tutorialspoint.com/gson/index.htm
UPDATE: If you really want to use JSONObject then use its constructor with a string parameter which parses your JSON string automatically.
val jsonObject = JSONObject(data)
Best way is using kotlinx.serialization. turn a Kotlin object into its JSON representation and back marking its class with the #Serializable annotation, and using the provided encodeToString and decodeFromString<T> extension functions on the Json object:
import kotlinx.serialization.*
import kotlinx.serialization.json.*
#Serializable
data class User(val name: String, val yearOfBirth: Int)
// Serialization (Kotlin object to JSON string)
val data = User("Louis", 1901)
val string = Json.encodeToString(data)
println(string) // {"name":"Louis","yearOfBirth":1901}
// Deserialization (JSON string to Kotlin object)
val obj = Json.decodeFromString<User>(string)
println(obj) // User(name=Louis, yearOfBirth=1901)
Further examples: https://blog.jetbrains.com/kotlin/2020/10/kotlinx-serialization-1-0-released/
I am adding 3 templates here for Kotlin Developers, It will solve json converting & parsing problems.
//Json Array template
{
"json_id": "12.4",
"json_name": "name of the array",
"json_image": "https://image_path",
"json_description": "Description of the Json Array"
}
Kotlin Model class
data class JsonDataParser(
#SerializedName("json_id") val id: Long,
#SerializedName("json_name") val name: String,
#SerializedName("json_image") val image: String,
#SerializedName("json_description") val description: String
)
Converting to Json String from the Model Class
val gson = Gson()
val json = gson.toJson(jsonDataParser)
Parsing from Json file/Strong
val json = getJson()
val topic = gson.fromJson(json, JsonDataParser::class.java)
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)