3

I have the following API response:

{  
   "data":{  
      "categoryFields":[  
         {  
            "name":"brand",
            "label":"Marca", 
            "values":[  
               {  
                  "key":53,
                  "value":"Alfa Romeo"
               },
               {  
                  "key":55,
                  "value":"Audi"
               }
            ]
         },
         {  
            "name":"year",
            "label":"Año", ,
            "dataType":"select",
            "values":[  
               {  
                  "key":2017,
                  "value":2017
               },
               {  
                  "key":2016,
                  "value":2016
               }
            ]
         },

      ]
   }
}

Ok, in the first categoryField the values are:

"key":53 INT,
"value":"Alfa Romeo", STRING

In the second categoryField the values are:

 "key":2017, INT
 "value":2017, INT

Also there's another type:

 "key":"string", STRING
 "value":"String", STRING

I need a class that can handle those types of data. Something like:

public class Value {

    @SerializedName("key")
    @Expose
    private DYNAMIC_TYPE key;

    @SerializedName("value")
    @Expose
    private DYNAMIC_TYPE value; 

}

How can I do that? Or there's a Gson function to help me with that?

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
suzy19
  • 41
  • 1
  • 4

3 Answers3

1

solution

public class CategoryValueDeserializer implements JsonDeserializer<CategoryValue> {
    @Override
    public CategoryValue deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();

        final JsonElement jsonKey = jsonObject.get("key");
        final String key = jsonKey.getAsString();

        final JsonElement jsonValue = jsonObject.get("value");
        final String value = jsonValue.getAsString();

        CategoryValue categoryValue = new CategoryValue();
        categoryValue.setKey(key);
        categoryValue.setValue(value);

        return categoryValue;

    }
}

//retrofit

 final Gson gson = new GsonBuilder()
                .registerTypeAdapter(Response.class, new CategoryValueDeserializer())
                .create();

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(END_POINT)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
suzy19
  • 41
  • 1
  • 4
1

Here is a working solution

First create a POJO class like below

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class KeyValuePair {
    @SerializedName("key")
    @Expose
    private String key;
    @SerializedName("value")
    @Expose
    private Object value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }
}

Then for Gson to serialize this class properly use this code

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;

import java.lang.reflect.Type;

public class KeyValuePairDeserializer implements JsonDeserializer<KeyValuePair> {
    @Override
    public KeyValuePair deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();

        final JsonElement jsonKey = jsonObject.get("key");
        final String key = jsonKey.getAsString();

        final JsonElement jsonValue = jsonObject.get("value");
        Object value = jsonValue.getAsString();
        if (jsonValue.isJsonPrimitive()) {
            JsonPrimitive jsonPrimitive = jsonValue.getAsJsonPrimitive();
            if (jsonPrimitive.isBoolean())
                value = jsonValue.getAsBoolean();
            else if (jsonPrimitive.isString())
                value = jsonValue.getAsString();
            else if (jsonPrimitive.isNumber()){
                value = jsonValue.getAsNumber();
            }
        }
        KeyValuePair categoryValue = new KeyValuePair();
        categoryValue.setKey(key);
        categoryValue.setValue(value);
        return categoryValue;
    }
}

Register the adapter with Gson like this

 Gson provideGson() {
        return new GsonBuilder()
                .registerTypeAdapter(KeyValuePair.class, new KeyValuePairDeserializer())
                .create();
    }

Now you access the values by using getter methods like these

public String getString(String key) {
    return (String) value;
}

public int getInt(String key) {
    return ((Number) value).intValue();
}

public long getLong(String key) {
    return ((Number) value).longValue();
}

public float getFloat(String key) {
    return ((Number) value).floatValue();
}

public boolean getBoolean(String key) {
    return (boolean) value;
}
Rakesh Gopathi
  • 302
  • 1
  • 12
0

I always had something like dataType provided by BE. Then I could base on its value during deserialization. You've got dataType too, but only for Int, Int case.

Well, I'd do one of two things:

  • Talk with BE to send different dataType for every different case. This is good for types with many parameters and only few different dataTypes. Then I deserialize with JsonDeserializer to what I need, conditionally - based on dataType.
  • If you have only two values and three possible cases, it's easy to check via isString and others, as proposed in different answer.
PrzemekTom
  • 1,328
  • 1
  • 13
  • 34