java - 使用 GSON 序列化对象

标签 java android json serialization gson

如何使用 gson 将此对象序列化和反序列化为 json:

public class test{

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

@Expose
public int alpha;
}

我已经试过了:

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

其中 testInstance 是类 test 的实例,但由于 List 中的 Pair 结构,它无法正常工作。

最佳答案

您已经使用 excludeFieldsWithoutExposeAnnotation 方法配置了 Gson 对象。 来自 documentation :

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

你能改变 Pair 类吗?如果是,则必须向要序列化为 JSON 的每个属性添加 @Expose 注释。如果没有,您可以在您的程序中创建类似的类并添加注释。

关于java - 使用 GSON 序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17750372/

相关文章:

java - 使用 jooq 插入间隔数据

android - 将 SD 卡上的图像源提供给 phonegap 中的图像标签

android - PNG 在 Android 中失去透明度(如果它的所有像素都不透明)

java - 在安卓上打开文件

java - 从 Assets 文件夹中重新缩放图像以适合屏幕

java - 在 Spring 中解析 MongoRepository 的变量名称

Java方法重载——歧义

java - 通过 JSON 和 PHP 发送电子邮件后出现 NullpointerException

javascript - 自动将 json 操作为具有不同结构的对象

jquery - 尝试将 Google Places API 与 JQuery 的 getJSON 函数一起使用