1

我试图@JsonUnwrapped在 Jsonb(使用 Yasson)中实现相当于 Jacksons 的功能:

@Retention(RetentionPolicy.RUNTIME)
@JsonbTypeSerializer(UnwrappedJsonbSerializer.class)
public @interface JsonbUnwrapped {}

public class UnwrappedJsonbSerializer implements JsonbSerializer<Object> {

    @Override
    public void serialize(Object object, JsonGenerator generator, SerializationContext context) {
        context.serialize(object, new UnwrappedJsonGenerator(generator));
    }
}

public class UnwrappedJsonGenerator extends JsonGeneratorWrapper {

    private int level;

    public UnwrappedJsonGenerator(JsonGenerator delegate) {
        super(delegate);
    }

    @Override
    public JsonGenerator writeStartObject(String name) {
        return level++ == 0 ? this : super.writeStartObject(name);
    }

    @Override
    public JsonGenerator writeStartArray(String name) {
        return level++ == 0 ? this : super.writeStartArray(name);
    }

    @Override
    public JsonGenerator writeEnd() {
        return --level == 0 ? this : super.writeEnd();
    }
}

public class Person {

    @JsonbUnwrapped
    public Name getName() {
        return new Name();
    }

    public static class Name {

        public String getFirstName() {
            return "John";
        }

        public String getLastName() {
            return "Doe";
        }
    }
}

JsonbBuilder.create().toJson(new Person())

但这引发了一个异常javax.json.bind.JsonbException: Recursive reference has been found in class class Person$Name,因为我的UnwrappedJsonbSerializer 调用SerializationContext.serialize()与最初传递的对象相同。

有没有其他方法可以在不使用Personor的自定义序列化程序的情况下实现这一目标Name

4

0 回答 0