Does anyone know how to parse extras, when receivi...
# android
t
Does anyone know how to parse extras, when receiving data from a service class?
Copy code
class DataReceiver : Service() {
//other service code
 override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val extra = intent.extras?.getString("extra")
        // extra = {amount=1234, type=string1, id=string2}
        return super.onStartCommand(intent, flags, startId)
    }
}
//this is kotlin
m
@Tariq Ebadi You can define a
data class
corresponding to the JSON string, and then convert it to an instance of the
data class
by using a popular JSON converter such as GSON. If you need more info let me know to help you. 🙂 https://stackoverflow.com/questions/44117970/kotlin-data-class-from-json-using-gson
t
Thank you for the help @Mohammadreza Khahani The solution is actually a lot simpler.
Copy code
val extra = intent.extras?.getString("extra")
val jsonObject = JSONObject(extra)
thats it haha. Then its super easy to map each item.
Copy code
val id = jsonObject.getString("id")
Or even add each one to a data class. No need to for gson. Because extras does not return a json object. I think you’ve made the mistake of assuming the object at hand is a json object, it is just a string. And this is from a service, so moving data is somewhat more complicated. The correct approach is service->repository(singleton)->viewModel
👍 1
m
@Tariq Ebadi I'm glad using
JSONObject
satisfied the requirement for the task. 👍 I understand your requirement because GSON can parse JSON string to an instance of the corresponding class automatically, and vice versa. 😉 You could take a look at the pros and cons of
JSONObject
vs GSON library when you have some time. 🦾 https://stackoverflow.com/questions/42641301/org-json-jsonobject-vs-gson-library-jsonobject
g
@Mohammadreza Khahani @Tariq Ebadi Actually serialization was not an issue as I confirmed in my query before updating kotlin version it was working fine . on taking deep insights i find out in shared folder we have kotlin("plugin.serialization") which need to be updated to same version i.e. "1.9.10" and finally it's working fine , Thanks for your time ..!!
💪 1