使用Gson TypeAdapter反序列化动态JSON

时间:2019-10-05 10:19:35

标签: json gson json-deserialization

我有这样的POJO:

   private String httpStatus;
   private String message;

   // getter setter
}

我需要反序列化具有动态格式的json。

例如,有时候我的json对象会像这样:

{
    "httpStatus": 422,
    "message": "The given data was invalid.",
    "data": {
        "fields": {
            "user.name": [
                "The user.name field is required."
            ],
            "location.name": [
                "The location.name field is required."
            ]
        }
    }
}

有时,fields部分上的字段名称可能会像这样:

{
    "httpStatus": 422,
    "message": "The given data was invalid.",
    "data": {
        "fields": {
            "phone": [
                "The phone field is required."
            ]
        }
    }
}

我正在尝试通过注册gson TypeAdapter来解决此问题,但仍未成功。

final GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Error.class, new ErrorTypeAdapter());
        gsonBuilder.setPrettyPrinting();
        final Gson gson = gsonBuilder.create();

所以我的目标是从data-> fields-> phone->获取信息错误消息,获取第一个字符串并将其放在message字段中。

所以当我有这样的json字符串时:

String errorJson = "{\n" +
                "\"httpStatus\": 422,\n" +
                "\"message\": \"The given data was invalid.\",\n" +
                "\"data\": {\n" +
                "\"fields\": {\n" +
                "\"phone\": [\n" +
                "\"The phone field is required.\"\n" +
                "]\n" +
                "}\n" +
                "}\n" +
                "}";

然后我尝试通过调用以下方式反序列化:

final Error error = gson.fromJson(errorJson, Book.class);
System.out.println(error.getMessage);

它应该打印: The phone field is required

不是The given data was invalid.

任何人都可以给我有关如何创建ErrorTypeAdapter类以解决此问题的示例? 谢谢。

0 个答案:

没有答案