[英]How to parse array of numeric values in a JSON to Java object with Jsonb
I love how easy it is to map JSON data to a Java object with Jsonb, but I seem to have stumbled upon a not well-documented use-case...
鑒於此 json 數據:
{
"id": "test",
"points": [
[
-24.787439346313477,
5.5551919937133789
],
[
-23.788913726806641,
6.7245755195617676
],
[
-22.257251739501953,
7.2461895942687988
]
]
}
什么可以用作 object 類型來存儲點值?
import jakarta.json.bind.annotation.JsonbProperty;
public class Temp {
@JsonbProperty("id")
private String id;
@JsonbProperty("points")
private ??? points;
// Getters-Setters
}
所以我可以創建臨時對象:
import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
Jsonb jsonb = JsonbBuilder.create();
Temp temp = jsonb.fromJson(jsonString, Temp.class);
到目前為止,我已經嘗試了以下方法:
List<Point>
--> “無法將 JSON 數組反序列化為:class java.awt.Point”List<Point2D>
--> “無法將 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() { }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.