Android 如何使用Gson将JSON对象解析为自定义对象?
我将以下JSON对象作为字符串:Android 如何使用Gson将JSON对象解析为自定义对象?,android,gson,Android,Gson,我将以下JSON对象作为字符串: [{"Add1":"101","Description":null,"ID":1,"Name":"Bundesverfassung","Short":"BV"},{"Add1":"220","Description":null,"ID":2,"Name":"Obligationenrecht","Short":"OR"},{"Add1":"210","Description":null,"ID":3,"Name":"Schweizerisches Zivilge
[{"Add1":"101","Description":null,"ID":1,"Name":"Bundesverfassung","Short":"BV"},{"Add1":"220","Description":null,"ID":2,"Name":"Obligationenrecht","Short":"OR"},{"Add1":"210","Description":null,"ID":3,"Name":"Schweizerisches Zivilgesetzbuch","Short":"ZGB"},{"Add1":"311_0","Description":null,"ID":4,"Name":"Schweizerisches Strafgesetzbuch","Short":null}]
现在,我创建了一个类,该类表示以下结果之一:
public class Book {
private int number;
private String description;
private int id;
private String name;
private String abbrevation;
public Book(int number, String description, int id, String name, String abbrevation) {
this.number = number;
this.description = description;
this.id = id;
this.name = name;
this.abbrevation = abbrevation;
}
}
现在我想用它将JSON对象解析成一个Book对象列表。我试过这样做,但显然不起作用。我怎样才能解决这个问题
public static Book[] fromJSONtoBook(String response) {
Gson gson = new Gson();
return gson.fromJson(response, Book[].class);
}
我不确定GSON是否知道如何将JSONObject的JSONArray映射到Book类。我对这个设置有一些观察
- 如果您注意到,JSONObject 组成JSONArray并包含 属性“Add1”和“Short”,但 你的图书课没有课 具有相同名称的属性
- 应注意类型。我是 猜测“Add1”将要映射 到number属性(纯a) 猜一猜),类型为 JSONObject,但它是 书本课
- 我想知道这件事 图书类属性需要 匹配JSONObject的大小写
- 您的Book类不包含 公共默认构造函数,我 我认为GSON需要绘制地图
以上只是我的几个建议,这些建议不一定正确或完整,因为我以前没有使用过GSON。答案很简单,您必须使用注释
SerializedName
来指示JSON对象的哪个部分用于将JSON对象解析为Book对象:
public class Book {
@SerializedName("Add1")
private String number;
@SerializedName("Description")
private String description;
@SerializedName("ID")
private int id;
@SerializedName("Name")
private String name;
@SerializedName("Short")
private String abbrevation;
public Book(String number, String description, int id, String name, String abbrevation) {
this.number = number;
this.description = description;
this.id = id;
this.name = name;
this.abbrevation = abbrevation;
}
}
书籍类中的所有变量都为空。这是我使用Jackson时的首选方法。我以为格森有,但我不知道我脑子里想的是什么+1以获得另一个优秀的实现。@RoflcoptrException如何序列化内部JSON对象的名称。我试图,
@SerializedName(“activity.id”)
引用另一个JSON对象中的“activity”对象内的“id”键,但它返回null。但是,外部JSON对象中“activity”对象的同级就可以了。