如何使用Gson将JSON对象解析为自定义对象?

1 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 Zivilgesetzbuch","Short":"ZGB"},{"Add1":"311_0","Description":null,"ID":4,"Name":"Schweizerisches Strafgesetzbuch","Short":null}]
Run Code Online (Sandbox Code Playgroud)

现在我创建了一个代表其中一个结果的类:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

现在我想使用Gson将JSON对象解析为Book对象列表.我试过这种方式,但显然它不起作用.我该如何解决这个问题?

public static Book[] fromJSONtoBook(String response) {
        Gson gson = new Gson();
        return gson.fromJson(response, Book[].class);
    }
Run Code Online (Sandbox Code Playgroud)

Rof*_*ion 7

答案非常简单,您必须使用注释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;
    }

}
Run Code Online (Sandbox Code Playgroud)