i have the following Json string, which I\'m suppose to deserialize. The problem is: since this string comes from a server I can\'t change it and I need to deserialize as PO
You can use TypeAdapterFactory to do the conversion. Here is a factory that will add that functionality to all of your List
member types --
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
public class SingletonListTypeAdapterFactory implements TypeAdapterFactory {
public TypeAdapter create(Gson gson, TypeToken typeToken) {
Type type = typeToken.getType();
if (typeToken.getRawType() != List.class
|| !(type instanceof ParameterizedType)) {
return null;
}
Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
TypeAdapter> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
TypeAdapter arrayAdapter = gson.getDelegateAdapter(this, typeToken);
return (TypeAdapter) newSingtonListAdapter((TypeAdapter
As bonus, it also serializes in the same way, if needed. If you also want to serialize as array, replace the write
method with a call to arrayAdapter.write
.
To you, add to your gson when building --
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new SingletonListTypeAdapterFactory())
.create();