gpt4 book ai didi

java - 用于自定义值序列化的 Jackson 自定义注释

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:10 25 4
gpt4 key购买 nike

我正在尝试创建会影响序列化值的自定义 jackson 注释。

含义:

class X {
@Unit("mm") int lenght;
...
}

现在序列化对象 X(10) 会导致:

{
"lenght" : "10 mm"
}

我怎样才能做到这一点?

最佳答案

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// Create own annotation storing your unit value

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@interface Unit {
String value();
}

// Create custom serializer checking @Unit annotation

class UnitSerializer extends StdSerializer<Integer> implements ContextualSerializer {

private String unit;

public UnitSerializer() {
super(Integer.class);
}

public UnitSerializer(String unit) {
super(Integer.class);
this.unit = unit;
}

@Override
public void serialize(Integer value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(String.format("%d %s", value, unit));
}

@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
String unit = null;
Unit ann = null;
if (property != null) {
ann = property.getAnnotation(Unit.class);
}
if (ann != null) {
unit = ann.value();
}
return new UnitSerializer(unit);
}
}

@NoArgsConstructor
@AllArgsConstructor
@Data
class X {
@JsonSerialize(using = UnitSerializer.class)
@Unit("mm")
private int length;
}

public class Runner {
public static void main(String[] args) throws JsonProcessingException {

X x = new X(10);
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(x));
}
}

结果:

{"length":"10 mm"}

关于java - 用于自定义值序列化的 Jackson 自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43342097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com