java - Gson反序列化具有不同值类型的json

标签 java android json gson

我正在尝试使用 Gson 反序列化一个 JSONArray,一个值的类型可以变化,值“in_wanted”可以是 booleanJSONObject.

in_wanted 作为 boolean 值:

{
"movies": [
        {
            "title": "example boolean",
            "in_wanted": false
        }
    ]           
}

in_wanted 作为 JSONObject:

{
"movies": [
        {
            "title": "example object",
            "in_wanted": {
                "profile": {
                    "value": false
                }
            }
        }
    ]           
}

只要对象可用,我就需要它,并且只要“in_wanted”的值为 boolean 值,我就需要一个反序列化器来返回 null。使用 Gson 执行此操作的最佳方法是什么?

最佳答案

您可以使用自定义反序列化器执行此操作。一开始我们应该创建可以代表您的 JSON 的数据模型。

class JsonEntity {

    private List<Movie> movies;

    public List<Movie> getMovies() {
        return movies;
    }

    public void setMovies(List<Movie> movies) {
        this.movies = movies;
    }

    @Override
    public String toString() {
        return "JsonEntity [movies=" + movies + "]";
    }
}

class Movie {

    private String title;
    private Profile in_wanted;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Profile getIn_wanted() {
        return in_wanted;
    }

    public void setIn_wanted(Profile in_wanted) {
        this.in_wanted = in_wanted;
    }

    @Override
    public String toString() {
        return "Movie [title=" + title + ", in_wanted=" + in_wanted + "]";
    }
}

class Profile {

    private boolean value;

    public boolean isValue() {
        return value;
    }

    public void setValue(boolean value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.valueOf(value);
    }
}

现在,当我们拥有所有需要的类时,我们应该实现新的自定义反序列化器:

class ProfileJsonDeserializer implements JsonDeserializer<Profile> {
    @Override
    public Profile deserialize(JsonElement jsonElement, Type type,
            JsonDeserializationContext context) throws JsonParseException {
        if (jsonElement.isJsonPrimitive()) {
            return null;
        }

        return context.deserialize(jsonElement, JsonProfile.class);
    }
}

class JsonProfile extends Profile {

}

请查看 JsonProfile 类。我们必须创建它以避免“反序列化循环”(棘手的部分)。

现在我们可以用测试方法测试我们的解决方案了:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Profile.class, new ProfileJsonDeserializer());
Gson gson = builder.create();

JsonEntity jsonEntity = gson.fromJson(new FileReader("/tmp/json.txt"),
        JsonEntity.class);
System.out.println(jsonEntity);

关于java - Gson反序列化具有不同值类型的json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16992891/

相关文章:

java - 如何使变量等待用户按下四个按钮之一?

android - 使用额外的模块为 android 构建 opencv 3.0

java - 如何将单个子 xml 元素转换为 Json 数组

javascript - 如何使用 JSON 在 angularjs 中创建双向绑定(bind)?

Android 创建带有圆角的自定义按钮

php - JSON 和 JSONP 有什么区别?

java - 在 Spring 批处理中处理两个文件

java - 匹配器不返回唯一结果

来自 XML 代码的 Java GetAttribute

用于检查输入名称的 Java 正则表达式