如何知道一个大java对象的json结构?

ogsagwnx  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(288)

我有一个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"
}
0dxa2lsx

0dxa2lsx1#

我更喜欢使用一种叫做“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);

maven回购中的Jackson依赖

r6hnlfcb

r6hnlfcb2#

你可以用 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)
2ic8powd

2ic8powd3#

您可以使用gson、fastjson或jacksonhttps://www.2json.net/article/45

相关问题