【问题标题】:Using GSON to serialize only nested JSON使用 GSON 仅序列化嵌套的 JSON
【发布时间】:2016-07-29 02:08:44
【问题描述】:

我有一个 API 可以返回一些可以说是有用的元数据以及请求的数据本身。它看起来像这样:

{
"success": true,
"messages": [],
/* other metadata */
"result":  { /* fields with useful data */ }
}

所以,基本上我只想序列化嵌套在“结果”字段内的内容,最好仍然能够使用元数据(检查真/假的“成功”并阅读消息可能很有用)。

我以为我可以使用 JSONObject 来分离“结果”和其他元数据,但是这个管道感觉有点开销。有没有办法纯粹使用 GSON 来做到这一点?

另一个问题是我使用 Retrofit,它有一个非常简洁的纯 GSON 工作流程。如果以上是处理此类 API 的唯一适当方法,我应该如何将其集成到 Retrofit 工作流程中?

【问题讨论】:

标签: java json api gson retrofit


【解决方案1】:

向您的改造建筑商添加:

.addConverterFactory(new GsonConverterFactory(new GsonBuilder()
                    .registerTypeAdapter(Result.class, new JsonDeserializer<Result>() {
                        @Override
                        public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                            if(!(((JsonObject) json).getAsJsonPrimitive("success")).getAsBoolean()) {
                                return null;
                            }
                            JsonObject result = ((JsonObject) json).getAsJsonObject("result");
                            return new Gson().fromJson(result, Result.class);
                        }
                    }).create()))

当然还有 npe 和其他检查 :)

【讨论】:

    【解决方案2】:

    使用@Expose 注解创建一个 POJO 并使用 serialization = true/false。如果你只想序列化成功,那么你的 POJO 应该是这样的。

    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class POJO {
        @SerializedName("success")
        @Expose(serialize = true, deserialize = false)
        private Boolean success;
        ///Your getter / setter methods
    }
    

    我已经在 Retrofit 上面使用了这个,它工作正常。

    希望这会有所帮助!

    编辑:

    您还需要在创建改造服务时提及这一点

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YOUR_BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
                .build();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      相关资源
      最近更新 更多