Parsing with Moshi in Android
Another excellent and super-easy library from Square. Moshi is an open source library, which helps you to parse JSON to model class (Java Objects) and vice versa.
So why Moshi and not Manual Parsing?
If you want to learn the basics of Parsing, take a simple JSON response and parse it manually. But if you intend to use REST APIs in your Android Application, you should pick a library for that because as the JSON response becomes complex, it is hard to keep track of your manual parsing logic. Moshi and GSON libraries are good options, but you can explore more.
( Once there was an online challenge where I had to write a Meeting Scheduling Application. A part of the application was reading data from a JSON file. I decided to parse the file manually. I got so bogged down with Parsing that I could barely write the main Scheduling Algorithm in time. )
How to convert JSON response to Java objects using Moshi?
“Analyze first, then Code.”
a) Analysis of JSON response
For better understanding, I have taken a relatively less complicated JSON response. Just give a 30-sec look at the image, and you will understand how you can think of a respective POJO class (RIGHT) from analyzing JSON response (LEFT).
The analysis gives you a rough idea about the Model class. Notice that the JSON response has an array of Person objects, so we will have a list of Person objects ( List<Person>).
Conclusion: JSONResponse — -→ MOSHI — -> List<Person>
b) Code
Now the analysis is done. We can jump straight right in the coding part. But the question is how to do that with Moshi?
Simple! You can code that in Three simple steps.
1. Create a Moshi objectMoshi moshi = new Moshi.Builder().build();
2. Create an Adapter Type type = Types.newParameterizedType(List.class, Person.class); JsonAdapter<List> adapter = moshi.adapter(type);
3. Get output
List<Person> persons = adapter.fromJson(jsonResponse);
Done!
You can see an example with full code implementation Rest call using Volley and JSON parsing using Moshi.
Putting up content takes a lot of time and effort 😓.
👏 clap 👏 If you think you learned something from this article.You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.
Read More:
What is addToBackStack in Fragment