gpt4 book ai didi

java - GSON将json值反序列化为Java对象

转载 作者:行者123 更新时间:2023-11-30 06:08:26 25 4
gpt4 key购买 nike

我有以下 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: Not a JSON Object: 1

我不想将 aPrice 更改为 Json 对象。

问题是 - 我可以以某种方式告诉 GSON 从 Json 值构造货币对象,而不是为整个 Item 类创建反序列化器吗?

最佳答案

首先,您应该创建一个实现 JsonDeserializer 接口(interface)的 ItemDeserializer 类。

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

关于java - GSON将json值反序列化为Java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50777624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com