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()
}
}
You can call the BeagleJsonSerializationFactory to delegate the responsability to serialize/deserialize beagle components of your custom types.
Example:
private const val KEY_NAME = "name"
interface Person {
val name: Text // This attribute should be serialized/deserialized by the Beagle platform
}
data class PersonImpl(override val name: Text) : Person
@RegisterBeagleAdapter
class PersonAdapter(private val serializer: BeagleJsonSerializer = BeagleJsonSerializerFactory.serializer) :
BeagleTypeAdapter<Person> {
override fun fromJson(json: String): Person {
val rootObject = JSONObject(json)
val nameJsonObject = rootObject.getJSONObject(KEY_NAME)
val text = serializer.deserializeComponent(nameJsonObject.toString())
return PersonImpl(name = text as Text)
}
override fun toJson(type: Person): String {
val rootObject = JSONObject()
rootObject.put(KEY_NAME, serializer.serializeComponent(type.name))
return rootObject.toString()
}
}
@RegisterWidget
data class TextWithPersonName(
val person: Person,
) : WidgetView() {
override fun buildView(rootView: RootView): TextView = TextView(rootView.getContext()).also {
it.setTextColor(Color.BLACK)
observeBindChanges(rootView, it, person.name.text) { personName ->
it.text = personName
}
}
}
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.