如何实现与@JsonUnwrap等效的Gson [英] How to implement a Gson equivalent of @JsonUnwrap

查看:127
本文介绍了如何实现与@JsonUnwrap等效的Gson的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Gson没有类似的功能,但是有没有办法像@JsonUnwrap那样增加对解包Json字段的支持?

I know Gson doesn't come with a similar feature, but is there a way to add support for unwrapping Json fields the way @JsonUnwrap does?

目标是允许使用以下结构:

The goal is to allow a structure like:

public class Person { 
    public int age; 
    public Name name; 
} 

public class Name { 
    public String first;
    public String last; 
}

被(反)序列化为:

{
  "age" : 18, 
  "first" : "Joey", 
  "last" : "Sixpack" 
}

代替:

{
   "age" : 18, 
    "name" : {
        "first" : "Joey",
        "last" : "Sixpack"
    } 
 }

我知道它可能会变得相当复杂,因此我并没有在寻求一个完整的解决方案,如果可行的话,只是一些高级指南.

I understand it could get fairly complex, so I'm not looking for a full solution, just some high-level guidelines if this is even doable.

推荐答案

当前,没有简单的方法可以做到这一点.无论如何,这里有一些使它起作用的指针/替代方法.

Currently, there is no easy way to do that. Here are anyway some pointers/alternative ways to make it work.

GsonFire : GsonFire 实现了Gson缺少的一些有用功能.虽然尚不提供自动包装/展开功能,但它可能是创建自定义逻辑的一个很好的起点.

GsonFire: GsonFire implements some useful features missing from Gson. While it does not yet offer automatic wrapping/unwrapping, it may be a good starting point to create your custom logic.

如果您只需要序列化,则可以在Person中为firstlast添加吸气剂,并使用可以当Gson反序列化JSON时使用setter吗?).

If you only need serialization, you can add getters for first and last in Person and use @ExposeMethodResult to serialize them. Unfortunately, setters are not supported (cf. Is possible to use setters when Gson deserializes a JSON?).

支持序列化的另一种方法是遵循将字段移动到父对象.

Another way to support the serialization is to follow the advices from How to move fields to parent object.

自定义TypeAdapters :支持序列化和反序列化的唯一方法之一就是创建自定义TypeAdapter.这不是通用的,但适合您的用例.

Custom TypeAdapters : on of the only ways to support both serialization and deserialization is to create custom TypeAdapters. This won't be generic, but it will suit your usecase.

线程将嵌套对象序列化为属性已经给出了示例,因此我在这里不再重复.

The thread Serialize Nested Object as Attributes already gives you examples, so I won't repeat them here.

这篇关于如何实现与@JsonUnwrap等效的Gson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆