【问题标题】:How to know json structure of a big java object?如何知道大java对象的json结构?
【发布时间】:2021-03-17 19:54:30
【问题描述】:

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

【问题讨论】:

  • 你可以使用像 swagger/openapi 这样的工具来为你生成这个输出。

标签: java json jsonconvert


【解决方案1】:

您可以使用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)

【讨论】:

  • 哦,好吧,让我看看。谢谢(我已经编辑了我的问题)
  • 不@Saad,它不起作用。我没有json。如果我提供数据,Gson 将打印 Json。正确的?我没有任何数据/我不知道提供数据的 Json 结构。我需要知道结构,以便我可以提供填充的 json 数据。
  • 在创建 java 对象时,为什么不使用您在问题中提供的示例数据。创建 Java 对象后,您可以使用 Gson 创建 JSON 字符串。获得 JSON 字符串后,您可以稍后根据需要替换其中的数据。
  • 嗯。它有很多!并且有多个 POJO 要做。我只是提供了一个示例数据来了解预期结果。当然,我必须尝试一些示例数据,但在我这样做之前想搜索/询问。
【解决方案2】:

我更喜欢使用名为“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 Dependency 在 Maven 仓库中

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多