简体   繁体   English

使用GSON序列化对象

[英]Serialize object using GSON

How can I serialize and deserialize this object with gson to json: 如何使用gson到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. 其中testInstance是类测试的一个实例,但由于List中的Pair结构,它不起作用。

You have configured Gson object using excludeFieldsWithoutExposeAnnotation method. 您已使用excludeFieldsWithoutExposeAnnotation方法配置了Gson对象。 From documentation : 来自文档

Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation. 配置Gson以排除所有字段,使其不考虑没有Expose批注的序列化或反序列化。

Could you change Pair class? 你能改变Pair类吗? If yes, you have to add @Expose annotation to each property which you want serialize to JSON. 如果是,则必须将@Expose注释添加到要序列化为JSON的每个属性。 If no, you can create similar class in your program and add annotations. 如果不是,您可以在程序中创建类似的类并添加注释。

if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure . 如果对象是泛型类型,则由于Java Type Erasure而丢失泛型类型信息。 You can solve this problem by specifying the correct parameterized type for your generic type. 您可以通过为泛型类型指定正确的参数化类型来解决此问题。 Try parameterized type like List<String> . 尝试参数化类型,如List<String> This should work 这应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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