Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit + GSON deserializer

I have an object like this one:

"choice": {
    "000": {
             "id": "001",
             "label": "test",
             "status": "0"
     },
    "001": {
             "id": "001",
             "label": "test",
             "status": "0"
     },
    "002": {
             "id": "001",
             "label": "test",
             "status": "0"
     },
    "003": {
             "id": "001",
             "label": "test",
             "status": "0"
     },
    "004": {
             "id": "001",
             "label": "test",
             "status": "0"
     }
    },

How can I parse that object with Gson+Retrofit? Or generate a POJO? There is an easy way of doing this?

Many thanks!

like image 218
Chronos Avatar asked Apr 06 '15 20:04

Chronos


People also ask

What is Gson retrofit?

Retrofit is a very popular HTTP client library for Android. Using Retrofit makes it easy to parse API response and use it in your application. It has built-in GSON converter that can automatically parse HTTP response into an Object or any other types in Java that can be used in your code.

What is Gson converter in Android?

Google's Gson library provides a powerful framework for converting between JSON strings and Java objects. This library helps to avoid needing to write boilerplate code to parse JSON responses yourself. It can be used with any networking library, including the Android Async HTTP Client and OkHttp.

What is Gson converter factory?

public final class GsonConverterFactory extends Converter.Factory. A converter which uses Gson for JSON. Because Gson is so flexible in the types it supports, this converter assumes that it can handle all types.


2 Answers

The main idea that all that you have in choice json object is Map:

public class RootObject{
    Map <String,ChoiceEntry> choice;
}

public class ChoiceEntry{
    String id;
    String label;
    int status;
}
like image 194
x90 Avatar answered Oct 10 '22 07:10

x90


You can create a POJO by pasting that JSON code into this link: http://pojo.sodhanalibrary.com/.

You posted a snippet that isn't properly formatted. I believe you'll have a multi-class POJO, and that is tricky to work with for certain uses such as listviews.

Let me know how it goes. Retrofit's really nice to use, but extremely annoying to figure out!

like image 33
Bruno Carrier Avatar answered Oct 10 '22 07:10

Bruno Carrier