问题描述
我喜欢使用 Jsonb 将 JSON 数据映射到 Java 对象是多么容易,但我似乎偶然发现了一个没有很好记录的用例......
给定这个json数据:
<input type="number" id="a" oninput="calculate()" /> × 588 +
<input type="number" id="b" oninput="calculate()" /> × 28 +
<input type="number" id="c" oninput="calculate()" /> + 44032 =
<input type='text' id="result" readonly />
什么可以用作存储点值的对象类型?
kong migrations bootstrap
所以我可以创建临时对象:
{
"id": "test","points": [
[
-24.787439346313477,5.5551919937133789
],[
-23.788913726806641,6.7245755195617676
],[
-22.257251739501953,7.2461895942687988
]
]
}
到目前为止,我已经尝试了以下方法:
-
import jakarta.json.bind.annotation.JsonbProperty; public class Temp { @JsonbProperty("id") private String id; @JsonbProperty("points") private ??? points; // Getters-Setters }
--> “无法将 JSON 数组反序列化为:class java.awt.Point” -
import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; Jsonb jsonb = JsonbBuilder.create(); Temp temp = jsonb.fromJson(jsonString,Temp.class);
--> “无法将 JSON 数组反序列化为:class java.awt.Point2D”
解决方法
让我们试试吧:
@Data
public class Temp {
@JsonbProperty("id")
private String id;
@JsonbProperty("points")
private List<List<BigDecimal>> points;
public static void main(String[] args) {
String jsonString = "{\n" +
" \"id\": \"test\",\n" +
" \"points\": [\n" +
" [\n" +
" -24.787439346313477,\n" +
" 5.5551919937133789\n" +
" ],\n" +
" [\n" +
" -23.788913726806641,\n" +
" 6.7245755195617676\n" +
" ],\n" +
" [\n" +
" -22.257251739501953,\n" +
" 7.2461895942687988\n" +
" ]\n" +
" ]\n" +
"}";
Jsonb jsonb = JsonbBuilder.create();
Temp temp = jsonb.fromJson(jsonString,Temp.class);
System.out.println(temp);
}
}
,
要找出默认映射,请使用非通用字段并使用调试器观察它:
public class Test {
public static void main(String[] args) {
String json = "{\"id\":\"test\",\"points\":[[-24.787439346313477,5.555191993713379],[-23.78891372680664,6.724575519561768],[-22.257251739501953,7.246189594268799]]}";
Temp temp = JsonbBuilder.create().fromJson(json,Temp.class);
System.out.println(temp.points);
}
public static class Temp {
public String id = null;
public List points = null;
public Temp() {
}
}
}
,
因为我已经这样做了:更改 json 格式将允许这样做:
public class Test {
public static void main(String[] args) {
String json = "{\"id\":\"test\",\"points\":[ {\"x\" : 1.0,\"y\" : 2.0 },{\"x\" : 3.0,\"y\" : 4.0 } ] }";
Temp temp = JsonbBuilder.create().fromJson(json,Temp.class);
System.out.println(temp.points);
}
public static class Temp {
public String id = null;
public List<Point> points = null;
public Temp() { }
}
public static class Point {
public double x;
public double y;
public Point() { }
}
}