Serialize object using GSON

为君一笑 提交于 2020-01-30 06:23:10

问题


How can I serialize and deserialize this object with gson to json:

public class test{

@Expose
public List< Pair<Double,Double> > list;

@Expose
public int alpha;
}

I've tried this:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String str = gson.toJson(testInstance,test.class);

where testInstance is an instance of class test, but it's not working because of Pair structure in List.


回答1:


You have configured Gson object using excludeFieldsWithoutExposeAnnotation method. From documentation:

Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.

Could you change Pair class? If yes, you have to add @Expose annotation to each property which you want serialize to JSON. If no, you can create similar class in your program and add annotations.




回答2:


if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. You can solve this problem by specifying the correct parameterized type for your generic type. Try parameterized type like List<String>. This should work



来源:https://stackoverflow.com/questions/17750372/serialize-object-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!