Beagle offers a customized serializer/deserializer
set through a BeagleTypeAdapter
interface. With this Adapter
it is possible to map any class, including classes that represent concrete types, such as the Integer class. You can see the interface contract below:
interface BeagleTypeAdapter<T> {
fun fromJson(json: String) : T
fun toJson(type: T) : String
}
This example creates an adapter
for the Person
interface that is extended from the data class
PersonImpl
that has only a name
attribute as a String
type.
In order to create an adapter you must:
@ RegisterBeagleAdapter
. In this example we named this class as PersonAdapter
;PersonImpl
data class is implemented as an example.;adapter
(PersonAdapter) class from the BeagleTypeAdapter
Interface
, informing the class to be mapped on;fromJson
and toJson methods
, check out the example below:interface Person
data class PersonImpl(val name: String) : Person
@RegisterBeagleAdapter
class PersonAdapter : BeagleTypeAdapter<Person> {
override fun fromJson(json: String): Person {
val rootObject = JSONObject(json)
return PersonImpl(rootObject.getString(KEY))
}
override fun toJson(type: Person): String {
type as PersonImpl
val rootObject = JSONObject()
rootObject.put(KEY, type.name)
return rootObject.toString()
}
}
This method takes a JSONObject as a string and returns an instance of the mapped class (Person).
This method takes the mapped data type (Person) and returns a JSONObject as a string.
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.