【问题标题】:Is there way to associate arbitrary data structure with GSON parser?有没有办法将任意数据结构与 GSON 解析器相关联?
【发布时间】:2014-05-30 08:51:34
【问题描述】:

首先我见过this question,但我没有看到我的问题的完整答案,而且这个问题是在 2 年前提出的。

简介:

例如,我们有一个具有这种结构的 JSON:

{
    "name": "some_name",
    "description": "some_description",
    "price": 123,
    "location": {
        "latitude": 456987,
        "longitude": 963258
    }
}

我可以使用GSON library 将此 JSON 自动解析为我的对象的类。

为此,我必须创建描述 JSON 结构的类,如下所示:

public class CustomClassDescribingJSON {

    private String name;
    private String description;
    private double price;
    private Location location;

    // Some getters and setters and other methods, fields, etc

    public class Location {
        private long latitude;
        private long longitude;

    }

}

接下来我可以将 JSON 自动解析为对象:

String json; // This object was obtained earlier.
CustomClassDescribingJSON object = new Gson().fromJson(json, CustomClassDescribingJSON.class);

我有几种方法可以更改班级中的字段名称(用于编写更具可读性的代码或遵循语言指南)。以下之一:

public class CustomClassDescribingJSON {

    @SerializedName("name")
    private String mName;

    @SerializedName("description")
    private String mDescription;

    @SerializedName("price")
    private double mPrice;

    @SerializedName("location")
    private Location mLocation;

    // Some getters and setters and other methods, fields, etc

    public class Location {

        @SerializedName("latitude")
        private long mLatitude;

        @SerializedName("longitude")
        private long mLongitude;

    }

}

使用与上面相同的代码来解析 JSON:

String json; // This object was obtained earlier.
CustomClassDescribingJSON object = new Gson().fromJson(json, CustomClassDescribingJSON.class);

但我找不到改变班级结构的可能性。例如,我想使用下一个类来解析相同的 JSON:

public class CustomClassDescribingJSON {

    private String mName;
    private String mDescription;
    private double mPrice;

    private long mLatitude;
    private long mLongitude;

}

问题:

  1. 与标题相同: 有没有办法将任意数据结构与 GSON 解析器相关联?
  2. 也许还有其他库可以做我想做的事?

【问题讨论】:

标签: java json gson


【解决方案1】:

【讨论】:

  • 是的,这就是我想要的。非常灵活的决定。谢谢。
【解决方案2】:

只需将 JSON 字符串转换为 HashMap<String, Object>,然后通过简单地迭代来填充任何类型的自定义结构,或者在每个自定义对象类中创建一个构造函数,如下所示来填充字段。

class CustomClassDescribingJSON {
    public CustomClassDescribingJSON(Map<String, Object> data) {
       // initialize the instance member 
    }
}

示例代码:

Reader reader = new BufferedReader(new FileReader(new File("resources/json12.txt")));
Type type = new TypeToken<HashMap<String, Object>>() {}.getType();
HashMap<String, Object> data = new Gson().fromJson(reader, type);

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

输出:

{
    "price": 123.0,
    "location": {
      "latitude": 456987.0,
      "longitude": 963258.0
    },
    "description": "some_description",
    "name": "some_name"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多