gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:19:11 27 4
gpt4 key购买 nike

我想将传入的 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/

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