杰克逊将字段序列化为其他名称

杰克逊将字段序列化为其他名称

本文介绍了杰克逊将字段序列化为其他名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有要反序列化的JSON:

I have this JSON to deserialize:

{
    "first-name": "Alpha",
    "last-name": "Beta",
    "gender": "m"
}

我想将其序列化为2种不同的格式:

I want to serialize it to 2 different formats:

[A]

{
    "first-name": "Alpha",
    "last-name": "Beta",
    "gender": "m"
}

[B]

{
    "firstName": "Alpha",
    "lastName": "Beta",
    "gender": "m"
}

我能够将其序列化为1种格式:仅[A]或[B].这是将其序列化为[B]的代码:

I'm able to serialize it to 1 format: [A] only or [B] only. Here's my code to serialize it to [B]:

public String firstName;
public String lastName;
public String gender;

@JsonProperty("firstName")
public String getFirstNameCC() {
    return firstName;
}

@JsonProperty("first-name")
public void setFirstNameD(String firstName) {
    this.firstName = firstName;
}

@JsonProperty("lastName")
public String getLastNameCC() {
    return lastName;
}

@JsonProperty("last-name")
public void setLastNameD(String lastName) {
    this.lastName = lastName;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

我在 http://www.baeldung.com/jackson上了解了有关JsonView的信息. -json-view-annotation (第5节,自定义JSON视图),但它只会更改其值.我想像上面的例子一样更改字段名称.谁能对此提供见识?

I read about JsonView here http://www.baeldung.com/jackson-json-view-annotation (section '5. Customize JSON Views') but it only changes its value. I want to change field name as example above. Can anyone give insight on this?

推荐答案

我不确定我是否能完全理解您的问题,但是对于我所了解的,您可以执行以下操作来实现不同的序列化.

I am not sure I completly understand your question, but for what I could understand you can do something like this to achieve different serializtions.

创建一个自定义批注以容纳所有可能的不同序列化选项:

Create a custom annotation to hold all possible different serialization options:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomJsonProperty {
    String propertyName();

    String format();

    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List {
        CustomJsonProperty[] value();
    }

}

相应地注释您的班级:

@JsonSerialize(using = CustomJsonPropertySerializer.class)
public class Bar {

    @CustomJsonProperty.List({
        @CustomJsonProperty(propertyName = "first-name", format = "A"),
        @CustomJsonProperty(propertyName = "firstName", format = "B")
    })
    private String firstName;

    @CustomJsonProperty.List({
            @CustomJsonProperty(propertyName = "last-name", format = "A"),
            @CustomJsonProperty(propertyName = "lastName", format = "B")
    })
    private String lastName;

    @CustomJsonProperty.List({
            @CustomJsonProperty(propertyName = "gender-x", format = "A"),
            @CustomJsonProperty(propertyName = "gender", format = "B")
    })
    private String gender;

    @JsonIgnore
    private String format;

    //getters & setters

}

创建一个自定义序列化器来解释您的新注释:

Create a custom serializer to interpret your new annotation:

public class CustomJsonPropertySerializer extends JsonSerializer<Bar> {

    @Override
    public void serialize(Bar bar, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
            throws IOException {
        jsonGenerator.writeStartObject();

        Field[] fields = bar.getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object value = null;

            try {
                value = field.get(bar);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            if (field.isAnnotationPresent(CustomJsonProperty.List.class)) {
                CustomJsonProperty[] properties = field.getAnnotation(CustomJsonProperty.List.class).value();
                CustomJsonProperty chosenProperty = null;

                for (CustomJsonProperty c : properties) {
                    if (c.format().equalsIgnoreCase(bar.getFormat())) {
                        chosenProperty = c;
                        break;
                    }
                }

                if (chosenProperty == null) {
                    //invalid format given, use first format then
                    chosenProperty = properties[0];
                }

                jsonGenerator.writeStringField(chosenProperty.propertyName(), value.toString());
            }
        }

        jsonGenerator.writeEndObject();
    }
}

现在,您可以考虑属性名称的不同格式来序列化对象:

Now you can serialize your objects taking into consideration different formats for the property names:

public static void main(String[] args) throws IOException {
    Bar bar1 = new Bar("first", "last", "m", "A");
    Bar bar2 = new Bar("first", "last", "m", "B");

    ObjectMapper mapper = new ObjectMapper();
    String json1 = mapper.writeValueAsString(bar1);
    String json2 = mapper.writeValueAsString(bar2);

    System.out.println(json1);
    System.out.println(json2);

}

输出:

{"first-name":"first","last-name":"last","gender-x":"m"}
{"firstName":"first","lastName":"last","gender":"m"}

当然,上述序列化程序仅适用于Bar对象,但是可以通过在超类上使用abstract String getFormat();继承并更改自定义序列化器以接受超类类型而不是Bar来轻松解决.

Of course the above serializer only works for Bar objects, but that can easily be solved using inheritance with abstract String getFormat(); on the super class and changing the custom serializer to accept the super class type, instead of Bar.

也许有比创建自己的东西更简单的方法,但是我不知道.让我知道是否有不清楚的地方,我可以再次详细说明.

Maybe there is a simpler way than creating your own stuff, but I don't know about it. Let me know if something wasn't clear and I can elaborate it again.

这篇关于杰克逊将字段序列化为其他名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:42