【问题标题】:How can I use Jackson to convert a javafx.scene.paint.Color to and from JSON如何使用 Jackson 将 javafx.scene.paint.Color 与 JSON 相互转换
【发布时间】:2015-07-15 18:07:17
【问题描述】:

我正在尝试找到一个示例,但无济于事如何将 javafx.scene.paint.Color JSON 重构回 POJO。

当我创建 JSON 时,Color.RED 变成了这样:

{
  "annotationText" : "5/5/2015 12:18 PM",
  "pageNumber" : 0,
  "textColor" : {
  "red" : 1.0,
  "green" : 0.0,
  "blue" : 0.0,
  "opacity" : 1.0,
  "opaque" : true,
  "brightness" : 1.0,
  "hue" : 0.0,
  "saturation" : 1.0
  },
"fillColor" : null
}

我不确定如何重新解析它,以便将 Color.RED 放回我 POJO 上的 textColor 字段中。

任何指针将不胜感激。

谢谢!

【问题讨论】:

  • 查看this blog 自定义反序列化。您可以获取 redgreenblueopacity 的双精度值,并将它们传递给 Color constructor
  • 谢谢 - 效果很好!

标签: jackson javafx-8


【解决方案1】:

要反序列化纯 JavaFX Color 对象,可以使用:

public class ColorDeserializer extends JsonDeserializer<Color> {

    @Override
    public Color deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode node = p.getCodec().readTree(p);
        double red = node.get("red").doubleValue();
        double green = node.get("green").doubleValue();
        double blue = node.get("blue").doubleValue();
        double opacity = node.get("opacity").doubleValue();

        return new Color(red, green, blue, opacity);
    }

}

你必须在你的模块中注册反序列化器:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Color.class, new ColorDeserializer());
mapper.registerModule(module);

Color readValue = mapper.readValue(json, Color.class);

【讨论】:

    【解决方案2】:

    根据上面的评论 - 我能够让它像这样工作:

    public class AnnotationDeserializer extends JsonDeserializer<AnnotationDetail>{
    
        @Override
        public AnnotationDetail deserialize(JsonParser jp, DeserializationContext ctxt) 
          throws IOException, JsonProcessingException {
            AnnotationDetail detail = new AnnotationDetail();
    
            JsonNode node = jp.getCodec().readTree(jp);
    
            detail.setAnnotationText(node.get("annotationText").asText());
            detail.setPageNumber((Integer) ((IntNode) node.get("pageNumber")).numberValue());
    
            JsonNode textColorNode = node.get("textColor");
            double red =(Double) ((DoubleNode) textColorNode.get("red")).numberValue();
            double green = (Double) ((DoubleNode) textColorNode.get("green")).numberValue();
            double blue = (Double) ((DoubleNode) textColorNode.get("blue")).numberValue();
            double opacity = (Double) ((DoubleNode) textColorNode.get("opacity")).numberValue();
    
            detail.setTextColor(new Color(red, green, blue, opacity));
            return detail;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 2016-12-28
      • 2019-02-20
      • 1970-01-01
      • 2017-01-22
      • 2019-01-06
      • 2015-06-03
      • 1970-01-01
      相关资源
      最近更新 更多