GSON将字符串属性反序列化为对象

时间:2016-12-18 20:16:57

标签: java gson deserialization

我有以下类型的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] .country

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

1 个答案:

答案 0 :(得分: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);
}