[英]Simplest way to create json file from structured raw file in Java?
示例文件
x1 x2 y1 y2
12 20 30 40
13 14 15 16
我想像這樣創建一個json結構,
{ "coordinates" :
[
{"x1" : 12 , "x2" : 20 , "y1":30 , "y2":40},
{"x1" : 13 , "x2" : 14 , "y1":15 , "y2":16},
]
}
默認解決方案是拆分並加入原始文件。 不幸的是,結構化數據不是100%干凈的,有時值中也存在不規則空間。 處理這種轉換的最干凈的方法是什么?任何輕量級的JAVA庫都可以做到這一點?
只需創建一些作為JSON字符串副本的POJO類,然后使用GSON或Jackson庫將其轉換為JSON字符串即可。
只需逐行讀取文件,獲取坐標並填充下面的POJO類的對象。
樣例代碼:
class Coordinates {
private ArrayList<XY> coordinates;
// getter & setter
}
class XY {
private int x1, x2, y1, y2;
public XY(int x1, int x2, int y1, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
// getter & setter
}
樣例代碼:
Coordinates coordinates = new Coordinates();
ArrayList<XY> list = new ArrayList<XY>();
list.add(new XY(12, 20, 30, 40));
list.add(new XY(13, 14, 15, 16));
coordinates.setCoordinates(list);
System.out.println(new Gson().toJson(coordinates));
System.out.println(new ObjectMapper().writeValueAsString(coordinates));
輸出:
{
"coordinates": [
{
"x1": 12,
"x2": 20,
"y1": 30,
"y2": 40
},
{
"x1": 13,
"x2": 14,
"y1": 15,
"y2": 16
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.