繁体   English   中英

如何知道json结构大java object?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM