[英]How to know json structure of a big java object?
我有一個附有很多課程的 pojo。 想知道要傳遞給 API 的 JSON 結構。
有什么方法可以創建 json 結構(帶有一些假數據)?
示例:
public class Staff {
private String personName;
private Salary salary;
private String[] position; // Array
private List<Department> department; // List
private Map<String, Address> addressMap; // Map
// getters & setters of those too.
}
Department
內部有更多數量的 POJO(加入部門數據的人員)Salary
有每個名稱的差異。我試圖在不手動創建的情況下獲得 JSON 結構。
像這樣的東西(預期輸出)
{
"person_name": "person_name",
"salary": {
"joining_salary": "0",
"designation": {
"joining_designation": "joining_designation",
"some_data": "some_data"......
}
},
"department": {
"current_department": {
"latitude": 59.331132099999998,
"longitude": 18.066796700000001,
"address": {
"address_line": "address_line",
"city_name": "city_name",
"zip_code": "zip_code",
"country_code": "co" ....> Restricted to 2 charactors
}
}
},
"some_other": [
"...."
],
"some": "some"
}
您可以使用com.google.code.gson
庫
Maven 依賴關系如下
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
您可以嘗試以下方法,
Staff staff = new Staff();
// create your objects as required
Gson gson = new Gson();
// below jsonString will have the JSON structure of staff Object
String jsonString = gson.toJson(staff)
我更喜歡使用名為“Jackson”的特殊且非常強大的工具
它可以雙向轉換 POJO -> JSON 和 JSON -> POJO
它還適用於其他輸入格式,例如 YAML 等
用法簡單;
// Creates default JSON mapper
ObjectMapper mapper = new ObjectMapper();
// Initialize your root object (it could be not necessarily “Stuff”)
// including all nested classes and fields. Any dummy data is
// applicable for your purposes.
Staff staff = new Staff();
// Write object to JSON in file:
mapper.writeValue(new File("c:\\staff.json"), staff);
Jackson Maven 回購中的依賴關系
您可以使用 gson、fastjson 或 Jackson https://www.2json.net/article/45
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.