I have class in Flutter:
class Foo {
String id;
int power;
Foo (this.id, this.power);
Map toJson() => {
'id': id,
'power': power
};
}
I've created a instance of this object and pass it to Android via MethodChannel as a String
:
_myChannel.invokeMethod('custom_event', {
'foo': foo.toJson().toString(),
});
In Android I retrive that string and want to convert to Foo object on Android side so:
val fooString = call.method.argument<String>("foo")
//output: {id: my_id, power: 23}
val response = fooString?.let { Response(it) }
//output {"id":"my_id","power":"23"}
Helper class:
class Response(json: String) : JSONObject(json) {
val data = this.optJSONArray(null)
?.let { 0.until(it.length()).map { i -> it.optJSONObject(i) } } // returns an array of JSONObject
?.map { FooJson(it.toString()) } // transforms each JSONObject of the array into Foo
}
class FooJson(json: String) : JSONObject(json) {
val id: String = this.optString("id")
val power: String = this.optInt("power")
}
How I can convert response to my Kotlin's class?