How to know json structure of a big java object?

122 views Asked by At

I hava a pojo with lots of classes attached to it. Wanted to know the JSON structure to be passed to the API.

Is there any way to create the json structure (with some fake data)?

Example:

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.
}
  • The Department has more number of POJOs within it (person joining to the department data)
  • Salary has rivisions of each designations.
  • so and so.

I am trying to get a JSON struture of this without creating it manually.

Something like this (Expected output)

{
    "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"
}
3

There are 3 answers

4
Saad Sahibjan On

You can use the com.google.code.gson library

Maven dependency is as below

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

You can try the following,

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)
0
Grrzly On

I prefer using special and very powerful tool called “Jackson”

It can convert in both directions POJO -> JSON and JSON -> POJO

It also works with other input formats such as YAML etc

The usage is simple;

// 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 Dependency in Maven Repo

0
jack On

you can use the gson, fastjson or Jackson https://www.2json.net/article/45