【问题标题】:Gson deserialize json with varying value typesGson 反序列化具有不同值类型的 json
【发布时间】:2013-06-07 21:01:38
【问题描述】:

我正在尝试使用 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”的值为布尔值,我就需要一个反序列化器来返回 null。使用 Gson 执行此操作的最佳方法是什么?

【问题讨论】:

  • 如果您要映射到一个类,然后尝试天真地让 Gson 反序列化器工作,它应该让引用为空。

标签: java android json gson


【解决方案1】:

您可以使用自定义反序列化器来做到这一点。一开始我们应该创建可以代表您的 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);

【讨论】:

  • 这成功了,因为您怀疑@MikO 手动解析将是一项艰巨的任务。非常感谢你们的帮助!
【解决方案2】:

您可以进行手动解析,例如:

JsonParser parser = new JsonParser();
JsonObject rootObject = parser.parse(yourJsonString).getAsJsonObject();
JsonObject movieObject = rootObject
                           .getAsJsonArray("movies")
                           .get(0).getAsJsonObject();
JsonElement inWantedElement = movieObject.get("in_wanted");

//Check if "in_wanted" element is a boolean or an object
if (inWantedElement.isJsonObject()) {
    //Process the element as an object...
    //for example get the element "value"...
    boolean value = inWantedElement
                      .getAsJsonObject()
                      .getAsJsonObject("profile")
                      .getAsJsonPrimitive("value")
                      .getAsBoolean();
}
else if (inWantedElement.isJsonPrimitive()) {
    //Process the element as a boolean...
    boolean inWanted = inWantedElement.getAsBoolean();
}

注意:有关 JsonObjectJsonArrayJsonElement 等类型的更多信息,请参阅 Gson API documentation...

【讨论】:

  • 是否可以仅对 in_wanted 值执行此操作?所以我不必为数组中的其他值编写手动解析(默认解串器解析得很好)。
  • @Meatje:我认为有可能,编写自定义反序列化器,但在编写之前,您必须注意,其他解决方案不会比这个简单得多,如果您有那些 JSON响应我认为这更好......还是您只包含了一小部分实际 JSON 响应?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多