首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >GSON将JSON值反序列化为Java对象

GSON将JSON值反序列化为Java对象
EN

Stack Overflow用户
提问于 2018-06-10 03:10:30
回答 1查看 484关注 0票数 1

我有以下json对象:

代码语言:javascript
复制
{
    "aSize": 1,
    "aPrice": 1,
    "aName": "Ticket",
    "aDescription": "Tickets are required to unlock the story"
}

和Java对象:

代码语言:javascript
复制
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类创建反序列化程序?

EN

回答 1

Stack Overflow用户

发布于 2018-06-10 03:57:22

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

代码语言:javascript
复制
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;
    }
}

你可以这样叫它:

代码语言:javascript
复制
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);
 }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50777624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档