【发布时间】: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;
}
问题:
- 与标题相同: 有没有办法将任意数据结构与 GSON 解析器相关联?
- 也许还有其他库可以做我想做的事?
【问题讨论】:
-
试试 JSONGen:jsongen.byingtondesign.com