简体   繁体   中英

How to serialize List object in Gson

I have data returned from DB using the below method (method from spark-java framework ) below:

get("/data_on_page_load", "application/json", (Request request, Response response) -> {
    List<Post> list = Post.findAll(); // NEED TO SERIALIZE THE RESPONSE
    System.out.println("list is  " + list);
    return (list);
}, new JsonTransformer());

Data returned from DB:

 [Model: com.soul.seeker.models.Post, table: 'post', attributes: {created_at=2017-03-26 04:06:35.0, details=aaa, id=36, title=Eventsa, url=eventsa, userImage=assets/img/spiritual-icon4.png, username=null}]

Where Post.findAll(); is method from http://javalite.io/record_selection#finding-all-records to get all records

Model: com.soul.seeker.models.Post is the POJO class below:

public class Post extends Model{
   private String title;
   private String details;
   private String username;
   private String userImage;
   private String url;
   private List categories;

   //Getters and Setters removed for brevity
}

I am trying to serialize the out put using GSON TypeToken and TypeAdapter

ClassTypeAdapterFactory:

public class ClassTypeAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {

        if(!Class.class.isAssignableFrom(typeToken.getRawType())) {
            return null;
        }

        return (TypeAdapter<T>) new ClassTypeAdapter();
    }
}

ClassTypeAdapter:

public class ClassTypeAdapter extends TypeAdapter<Class<?>> {
    @Override
    public void write(JsonWriter jsonWriter, Class<?> clazz) throws IOException {
        if(clazz == null){
            jsonWriter.nullValue();
            return;
        }
        jsonWriter.value(clazz.getName());
    }

    @Override
    public Class<?> read(JsonReader jsonReader) throws IOException {
        if (jsonReader.peek() == JsonToken.NULL) {
            jsonReader.nextNull();
            return null;
        }
        Class<?> clazz = null;
        try {
            clazz = Class.forName(jsonReader.nextString());
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return clazz;
    }
}

Here I am using JsonTransformer which implements ResponseTransformer from spark-java ResponseTransformer interface

public class JsonTransformer implements ResponseTransformer {

    private Gson gson = new Gson();

    @Override
    public String render(Object model) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.registerTypeAdapterFactory(new ClassTypeAdapterFactory()).create();
        return gson.toJson(model);
    }
}

Now the problem is the json out put also contains serialized class instead of only returning List object of pojo class. I am new to Java & Gson serialization.

Can any one please help in implementing TypeAdapter to return only List object? for Example like this:

Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType();
String s = gson.toJson(list, listOfTestObject);
List<TestObject> list2 = gson.fromJson(s, listOfTestObject);

I think that you won't need to type a Response Transformer, you can use a new Gson object directly like the last snippet at the response transformer documentation . It would end up like this:

    get("/data_on_page_load", (req, res) -> {
        res.type("application/json; charset=UTF-8");
        List<Post> list = Post.findAll();
        System.out.println("list is  " + list);
        return list;
    }, new Gson()::toJson);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM