gpt4 book ai didi

java - 无法使用 jackson 反序列化器反序列化 java.awt.color

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

  public class TestJacksonColor {
public static void main(String [] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Color black = new Color(0, 0, 0);
String json = objectMapper.writeValueAsString(black);
Color backToObject = objectMapper.readValue(json, Color.class);
}
}

代码尝试使用 jackson objectmapper 将 java.awt.color 类序列化。获取生成的 json 字符串并将其反序列化回 java.awt.color 类。但是,在进行反序列化时,会发生以下错误。

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class java.awt.Color]: can not instantiate from JSON object

最佳答案

您需要自定义序列化器和反序列化器。有一些预建的modules周围,​​但我不知道处理 java.awt.Color 的一个。

下面是一个示例,它定义了序列化器/反序列化器对并注册了一个模块来处理 Color 对象:

public class JacksonColorTest {

public static class ColorSerializer extends JsonSerializer<Color> {
@Override
public void serialize(Color value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeFieldName("argb");
gen.writeString(Integer.toHexString(value.getRGB()));
gen.writeEndObject();
}
}

public static class ColorDeserializer extends JsonDeserializer<Color> {
@Override
public Color deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
TreeNode root = p.getCodec().readTree(p);
TextNode rgba = (TextNode) root.get("argb");
return new Color(Integer.parseUnsignedInt(rgba.textValue(), 16), true);
}
}

public static void main(String [] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Color.class, new ColorSerializer());
module.addDeserializer(Color.class, new ColorDeserializer());
objectMapper.registerModule(module);

Color testColor = new Color(1, 2, 3, 4);
String json = objectMapper.writeValueAsString(testColor);
Color backToObject = objectMapper.readValue(json, Color.class);

if (!testColor.equals(backToObject)) {
throw new AssertionError("round trip failed");
}
}
}

关于java - 无法使用 jackson 反序列化器反序列化 java.awt.color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42070673/

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