How to parse a JSON object into a custom object using Gson?
I have the following JSON object as a String:
[{"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}]
Now i created a class that represents one of the results:
public class Book {
private int number;
pri开发者_开发技巧vate 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;
}
}
Now I want to use Gson to parse the JSON object into a list of Book objects. I tried it this way, but obviously it doesn't work. How can I fix that?
public static Book[] fromJSONtoBook(String response) {
Gson gson = new Gson();
return gson.fromJson(response, Book[].class);
}
The answer is quite simple, you have to use the annotation SerializedName
to indicated which part of the JSON object is used to parse the JSON object to a Book object:
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;
}
}
I am not sure that GSON knows how to map your JSONArray of JSONObjects to your Book class. I have a couple observations about this setup.
If you notice, the JSONObjects which make up the JSONArray contain the properties "Add1" and "Short", but your Book class does not have properties that have the same names.
The types should be noted. I am guessing that "Add1" is going to map to the number property (purely a guess), and the type is String in the JSONObject, but it is an int in the Book class.
I am wondering whether the case of the Book class properties need to match the case of the JSONObject.
Your Book class does not contain a public default constructor, which I think GSON needs to map.
The above are just a couple suggestions I have, which are not necessarily correct or complete as I have not used GSON before.
精彩评论