【问题标题】:Spring RequestBody map JSON string to Point2D coordinatesSpring RequestBody 将 JSON 字符串映射到 Point2D 坐标
【发布时间】:2020-01-20 16:34:28
【问题描述】:

我想将传入的 JSON 字符串映射到我的 @PostMapping 中的自定义 POJO:

@PostMapping(value = "/classification", consumes = "application/json", produces = "application/json")
public ResponseEntity<String> getClassificationResults (
            @RequestBody Classification classification) {

     this.elasticSearchService.getSpatialData(classification);
  return ResponseEntity.ok(" ");
}

我的classification POJO

public class Classification {
    @JsonProperty
    private ArrayList<Point2D.Double> shapes;
    @JsonProperty
    private String [] colors;
    @JsonProperty
    private String [] pattern;
    @JsonProperty
    private Integer size;
...
}

这(当然)会导致错误:

JSON 解析错误:无法构造的实例 java.awt.geom.Point2D$Double(尽管至少存在一位创作者): 没有要反序列化的字符串参数构造函数/工厂方法 字符串值

数据示例:

"[[8.880321034663876,49.121984026160106], 
 [8.746452886806255,49.11327654230291], 
 [8.61786489671323,49.087497674922325],...]"

我的结果对象不能是 Point2D 对象中的 ArrayList,而是任何类型的 Array,它包含与示例相同的值 - 只是转换为数字。

我是否必须为这个问题指定我自己的 Jackson 反序列化器(我该怎么做?),还是更改 Classification 构造函数就足够了?

【问题讨论】:

  • 我不相信简单地修改你的 Classification 类会在这里工作。这里的问题是它是一个包含 2 个双精度数的数组。映射器不知道哪个是“x”,哪个是“y”,或者它们甚至是相关的(不在连接对象中,它们是数组的独立元素)。如果是我,我会使用我自己的反序列化器(以及我自己的 Point 类),但是对于您的应用程序来说最简单的就足够了。
  • 感谢您的回答。是的,这就是“重点”;D 如何创建自定义反序列化器? - 也许是杰克逊,因为这是 Spring 支持的。

标签: java json spring spring-boot jackson


【解决方案1】:

您可以实现自定义解串器或使用MixIn featurePoint2D 类定义Shape.ARRAY

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.json.JsonMapper;

import java.awt.geom.Point2D;
import java.util.List;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        JsonMapper jsonMapper = JsonMapper.builder()
                .addMixIn(Point2D.Double.class, Point2DDoubleMixIn.class)
                .build();

        String json = "[[8.880321034663876,49.121984026160106],[8.746452886806255,49.11327654230291],[8.61786489671323,49.087497674922325]]";

        TypeReference<List<Point2D.Double>> type = new TypeReference<List<Point2D.Double>>() {};
        List<Point2D.Double> shapes = jsonMapper.readValue(json, type);
        System.out.println(shapes);
    }
}

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
interface Point2DDoubleMixIn { }

另见:

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多