如何在不创建对象的情况下将 java class 格式结构转换为 json 格式结构

How to convert java class to json format structure without creating object

我需要记录多个微服务 api 调用,所以我有一个问题,如何直接从 java pojo class 中创建 json 字符串。我的意思是说,例如,

MyPojo.java

public class MyPojo {
String name;
List<String> address;
public MyPojo() {
    // TODO Auto-generated constructor stub
}
//setters and getters

}

现在我需要 pojo 的字符串 json 结构而不创建 class.May 对象的方式与 swagger api 创建 @RequestBody 对象的 json 结构的方式相同在网络中 UI.

类似于:

String jsonStruct=SomeUtil.convertPojoToJson(MyPojo.class)

那么它应该像这样:

{"name":"string","address":[]}

我的尝试:

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.Schema;

public class TEst {
public static void main(String[] args) throws JsonProcessingException {

    ObjectMapper obj = new ObjectMapper(); 

    MyPojo o=new MyPojo();
    o.setName("aa");
    List<String> l=Arrays.asList("a","s");
    o.setAddress(l);
    System.out.println(obj.writeValueAsString(o));

}
}

实际o/p:

 {"name":"aa","address":["a","s"]}

需要o/p:

 {"name":"string","address":["string"]}

关注:但我需要在不创建对象的情况下进行创建,因为实际上 pojo 很大并且不可能设置所有虚拟数据。

您可以使用 Podam

PODAM is a lightweight tool to auto-fill Java POJOs with data. This comes handy when developing unit tests. Thanks to PODAM users now have a one-liner that does all the work them.

在您的项目中添加 PODAM 依赖项

<dependency>
  <groupId>uk.co.jemos.podam</groupId>
  <artifactId>podam</artifactId>
  <version>[latest.version]</version>
  <!-- <scope>test</scope> -->
</dependency>
  • 如果您不想要默认值(随机数据),请定义您的 DataProviderStrategy
  • 定义 PodamFactory bean,使用 Data Provider Strategy
  • 初始化
  • 在您的代码中使用 PodamFactory bean
 PodamFactory factory = new PodamFactoryImpl();
 MyPojo myPojo = factory.manufacturePojo(MyPojo .class);
 // write it as json
 System.out.println(new ObjectMapper().writeValueAsString(myPojo));