有没有办法将任意数据结构与GSON解析器相关联?

时间:2014-05-30 08:51:34

标签: java json gson

首先,我见过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解析为object:

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. 也许还有其他图书馆可以做我想做的事情?

2 个答案:

答案 0 :(得分:1)

只需将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"
}

答案 1 :(得分:1)