【问题标题】:GSON deserialise a string attribute to an objectGSON 将字符串属性反序列化为对象
【发布时间】:2017-05-03 21:44:48
【问题描述】:

我有以下类型的 Json 响应 -

{
    userName:"Jon Doe",
    country:"Australia"
}

我的用户类看起来像这样 -

public class User{
    private String userName;
    private Country country;
}

GSON 解析失败并出现以下错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期为 BEGIN_OBJECT,但在第 3 行第 18 列路径为 STRING $[0].国家

有没有办法告诉 GSON 用我当前的 JSON 响应将国家解析为 Country 对象?

【问题讨论】:

  • 什么是国家?一个类还是一个枚举?
  • @roby Country 是一个类。
  • @AbhishekBhatia 谢谢你的链接。让我来看看吧。

标签: java gson deserialization


【解决方案1】:

您可以通过注册自定义反序列化器来实现此目的。

public static class Country {
    private String name;

    public Country(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Country{" + "name='" + name + '\'' + '}';
    }
}

public static class Holder {

    private String x;
    private Country y;

    public Holder() {
    }

    public void setX(String x) {
        this.x = x;
    }

    public void setY(Country y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Holder{" + "x='" + x + '\'' + ", y=" + y + '}';
    }
}


@Test
public void test() {
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(Country.class, (JsonDeserializer) (json, typeOfT, context) -> {
        if (!json.isJsonPrimitive() || !json.getAsJsonPrimitive().isString()) {
            throw new JsonParseException("I only parse strings");
        }
        return new Country(json.getAsString());
    });
    Holder holder = gson.create().fromJson("{'x':'a','y':'New Zealand'}", Holder.class);
    //prints Holder{x='a', y=Country{name='New Zealand'}}
    System.out.println(holder);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多