Open In App

Moshi Library for Android

Last Updated : 14 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Moshi, a JSON library developed by Square. Moshi enables us to serialise and deserialize JSON in a more efficient and straightforward manner. So, before we begin, let us divide the article into the sections listed below.

  1. Why do we need an Android library for serializing and deserializing?
  2. How do we make use of Moshi?
  3. Moshi’s characteristics
  4. Using Moshi in conjunction with List.
  5. Using Moshi in conjunction with Retrofit

Why do we need an Android library for serializing and deserializing?

When we make an API call in Android, we almost always get JSON as a response. We can either call that JSON and manually parse it to work with it, or we can use a library like Moshi to serialise and deserialize it for us. Using Moshi can help us reduce the number of lines we write and the likelihood of errors.

How do we make use of Moshi?

This section will explain how we would collaborate with Moshi. Assume we have a data class called GFG.

data class GFG(val courseName: String, val coursePrice: Int)

and suppose we have a variable called user, which is defined as:

val gfg= GFG("Spandan", "connectwithspandan@gmail.com")

We will now convert this to a JSON structure with the help of Moshi. We have a JsonAdapter class and a builder pattern to work with Moshi. As a result, we built Moshi with:

Kotlin




val gfgMoshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()


In this case, we’ve passed the User data class as a structure to which we’d like to perform the actions. Now, to convert the User class’s object to JSON, we use

someJsonAdap.toJson(gfg)

Moshi’s Features Moshi supports almost all data types by default, such as:

  1. Integer, Float, and so on
  2. Collections and Arrays
  3. Strings, Enums

Aside from the above-mentioned types, we can create our own in Moshi. Let us illustrate this with an example.

Kotlin




data class GFG(val courseName:CName)


We take two parameters called firstName and lastName in the Name class. Now, when we get a JSON from this class, we want the user’s full name, such as firstName + lastName. We can either do it manually every time we parse the JSON or add our own adapter and have Moshi do it for us. As a result, we’ll create a class called NameAdapter.

Kotlin




class CourseAdapter { }


And we’ll do our conversion within this class. We’ll add two new functions: fun fullName() and fun getIndividualNames(). The class now appears to be:

Kotlin




class GFGUserAdapter {
    @ToJson
    fun fullGFGUser(GFGUser: GFGUser): String {
         
    }
 
    @FromJson
    fun getIndividualGFGUsers(json: String): GFGUser {
       
    }
 
}


We have annotated fullName with ToJson and getIndividualNames with FromJson in this case. This means that when you use this adapter with Moshi, Moshi will search for annotations. Let’s say we want to concatenate both first and last names to return the full name in JSON; we’ll do that inside the fullName function, which is annotated with ToJson. Similarly, since we added the ToJson conversion for JSON parsing, we’d need to update the getIndividualNames function, which is annotated with FromJson and will convert JSON values to individual elements in the Name data class when mapping JSON to class.

Kotlin




@FromJson
fun getIndividualGFGUsers(fullGFGUser: String): GFGUser {
    val GFGUser = fullGFGUser.split(" ")
    return GFGUser(GFGUser[0], GFGUser[1])
}


In this case, we split the string fullName from the first empty space to get the two strings that are first name and last name in a string list.

Geektip: Please keep in mind that Moshi’s adapters are ordered by precedence, so you should always add the Kotlin adapter after your own custom adapters. Otherwise, the KotlinJsonAdapterFactory will be invoked and your custom adapters will be ignored.

Kotlin




@JsonClass(generateAdapter = true)
data class GFG(val gfgName: Name, @EmailCheck val gfg: India?)


As you can see, we have annotated the email with EmailCheck, which means that the check will only work with the email field if all of the EmailCheck annotations are present. The Name class remains unchanged

Using Moshi in conjunction with List

We will learn how to convert a List to a String and then a String to a List in this section. Consider the following scenario: we receive a list of objects from our server and need to store it in our app’s shared preferences. We’d like to convert the list of objects to string because it only saves a primitive data type and we’ll convert it back to a list when we need it.

Kotlin




val gfgMoshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads