java - Spring RequestBody 将 JSON 字符串映射到 Point2D 坐标

标签 java json spring spring-boot jackson

我想将传入的 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(" ");
}

我的分类POJO:

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

这(当然)会导致错误:

JSON parse error: Cannot construct instance of java.awt.geom.Point2D$Double (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value

数据示例:

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

我生成的对象不得是 Point2D 对象的 ArrayList,而是包含与示例相同的值的任何类型的 Array - 刚刚转换为数字。

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

最佳答案

您可以实现自定义反序列化器或使用 MixIn feature定义Shape.ARRAY对于 Point2D 类:

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 { }

另请参阅:

关于java - Spring RequestBody 将 JSON 字符串映射到 Point2D 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59827497/

相关文章:

java - 如何重新着色 GridView 项目

jquery - 从我的函数中删除 HTML

java - spring jdbc 模板返回空结果

Java Spring Thymeleaf 将枚举集合绑定(bind)到复选框时出错

java - Spring Integration - 在消息中添加自定义 header

java - 分类器 JSONObject 没有“伴生对象”,因此必须在此处初始化

java - ivy build - 不同版本的多个工件

java - Spring:@Component 与 @Bean

javascript - 如何传递jsonp格式的javascript代码并执行

java - 具有嵌套值的 JSON 到 POJO