我有以下json对象:
{
"aSize": 1,
"aPrice": 1,
"aName": "Ticket",
"aDescription": "Tickets are required to unlock the story"
}
和Java对象:
public class Item
{
private String aId;
private int aSize;
private Currency aPrice;
private String aName;
private String aDescription;
}
public class Currency
{
private int aPrice;
}
当我尝试反序列化Item对象时,我收到此错误:
com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:不是JSON对象:1
我不想将aPrice
更改为Json对象。
问题是 - 我可以告诉GSON从Json值构造Currency对象,而不是为整个Item类创建反序列化器吗?
答案 0 :(得分:1)
首先,您应该创建一个实现ItemDeserializer
接口的JsonDeserializer
类。
import com.google.gson.*;
import java.lang.reflect.Type;
public class ItemDeserializer implements JsonDeserializer<Item> {
public Item deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException
{
JsonObject jsonObject = jsonElement.getAsJsonObject();
Item item = new Item();
item.setaName(jsonObject.get("aName").getAsString());
item.setaSize(jsonObject.get("aSize").getAsInt());
item.setaPrice(new Currency(jsonObject.get("aPrice").getAsInt()));
item.setaDescription(jsonObject.get("aDescription").getAsString());
return item;
}
}
你可以这样称呼它:
public static void main(String args[]) {
String json = "{ \"aSize\": 1, \"aPrice\": 1, \"aName\": " +
"\"Ticket\", \"aDescription\": \"Tickets are required to unlock the story\" }";
GsonBuilder gsonBuilder = new GsonBuilder();
ItemDeserializer itemDeserializer = new ItemDeserializer();
gsonBuilder.registerTypeAdapter(Item.class, itemDeserializer);
Gson customGson = gsonBuilder.create();
Item item = customGson.fromJson(json, Item.class);
System.out.println(item);
}