Gson: How can I custom deserialize some fields only?

Created on 27 Feb 2016  路  2Comments  路  Source: google/gson

My shop json is:

 "shop":{
"name" : {
    "en" : "My Shop",
    "es" : "Mi Tienda" 
}, 
"order" : 0
}

And shop model is:

class Shop{
    public String name;
   public int order
}

So how can I deserialize that kind of Json to this model? Can I write a custom serializer for only "name" field?

Most helpful comment

You can use the @JsonAdapter annotation on the first for which you want to deserialize using custom logic. In your example, you would write a TypeAdapter or TypeAdapterFactory which handled selecting the correct language from the object and return the string value.

All 2 comments

You can use the @JsonAdapter annotation on the first for which you want to deserialize using custom logic. In your example, you would write a TypeAdapter or TypeAdapterFactory which handled selecting the correct language from the object and return the string value.

Thank you,

public class MultilingualStringAdapter extends TypeAdapter<String> {


@Override
public void write(JsonWriter out, String value) throws IOException {
    Log.d("multilingual test", value);
}

@Override
public String read(JsonReader in) throws IOException {
    String value = null;
    in.beginObject();
    while(in.hasNext()){
        String name = in.nextName();
        if(name.equals(Global.getAppLanguage().code)){
            value = in.nextString();
        }
        else {
            in.skipValue();
        }
    }
    in.endObject();
    return value;
}
}

solved my issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kdehairy picture kdehairy  路  43Comments

inder123 picture inder123  路  17Comments

GoogleCodeExporter picture GoogleCodeExporter  路  15Comments

GoogleCodeExporter picture GoogleCodeExporter  路  25Comments

GoogleCodeExporter picture GoogleCodeExporter  路  20Comments