import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class TestGson {
public static void main(String[] args) {
TestEntity t = new TestEntity();
List<String> lst = new ArrayList<String>();
lst.add("test");
t.collection = lst;
t.parametrizedCollection = lst;
Gson gson = new GsonBuilder().registerTypeAdapter(ArrayList.class, new TestAdapter()).create();
String json = gson.toJson(t);
System.out.println(json);
}
}
class TestEntity {
public Collection collection;
public Collection<String> parametrizedCollection;
}
class TestAdapter extends TypeAdapter<List> {
@Override
public List read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
//...
return new ArrayList();
}
@Override
public void write(JsonWriter out, List value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.beginArray();
for (Object element : value) {
out.value("TypeAdapted-" + element);
}
out.endArray();
return;