8

Dynamic JSON deserialization with Moshi & Retrofit

 2 years ago
source link: https://proandroiddev.com/dynamic-json-deserialization-moshi-retrofit-d4a28645b022
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Dynamic JSON deserialization with Moshi & Retrofit

How to deserialize raw JSON objects with Moshi & Retrofit

You have probably come across different JSON structures in a single response. The ways in which you parse it in the application can be different. Imagine we have the following JSON:

We can deserialize this JSON in different ways. A bad way to deserialize would be to put each property into a single object.

This is where we confuse ourselves and others with whom we share the code.

Why is this way bad?

The answer is simple. With this we set that the truck has a property that is related to the wingspan, which isn’t true.

This is where polymorphism comes in handy.

What is a polymorphism?

Polymorphism is the ability of an object to take on many forms.

In our example:

1*L1wi3YFcTBXHZvXRntVCPA.png

In the first step we defined the Vehicle sealed interface with abstract parameter type.

What is Sealed interface?

Sealed interfaces represent restricted class hierarchies that provide more control over inheritance.

You can read more about them here.

In the second and third steps, we added the appropriate classes for the different types, as well as Moshi's codegen annotations.

Now, we need to create a factory using PolymorphicJsonAdapterFactory.

What is PolymorphicJsonAdapterFactory?

A JsonAdapter factory for objects that include type information in the JSON. When decoding JSON Moshi uses this type information to determine which class to decode to. When encoding Moshi uses the object’s class to determine what type information to include.

Here we need to indicate which JSON property should be used to identify the specific class to be used. In our example it is type.

Finally, we need to add the factory to the Moshi builder.

What if we get a non-enum type in the response?

There we have a problem, this factory will not work well then. One solution is to add UNKNOWN as a new type inside VehicleType and define a default value within the factory.

0*yndhUDQecrujoUBQ

Photo by Antonio Janeski on Unsplash

Thats it. I hope it was helpful. :)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK