如何在不创建对象的情况下将Java类转换为json格式结构 [英] How to convert java class to json format structure without creating object
问题描述
我需要记录多个微服务api调用,所以我有一个问题,如何直接从java pojo类中创建json字符串.我的意思是说,
I need to document multiple microservices api call,so I have a question that how to create json string out of java pojo class directly. I mean say for example ,
MyPojo.java
MyPojo.java
public class MyPojo {
String name;
List<String> address;
public MyPojo() {
// TODO Auto-generated constructor stub
}
//setters and getters
}
现在我需要pojo的字符串json结构而不创建类的对象.可能与swagger api在Web UI中创建@RequestBody对象的json结构的方式相同.
now I need the string json structure of the pojo without creating object of the class.May be same the way swagger api creates json structure of @RequestBody object in web 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是巨大的,不可能设置所有虚拟数据.
CONCERN: But I need to create without creating object as in real the pojo is huge and not possible to set all dummy data.
推荐答案
您可以使用 Podam
PODAM是一种轻量级的工具,可以用数据自动填充Java 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依赖项
Add PODAM dependency in your project
<dependency>
<groupId>uk.co.jemos.podam</groupId>
<artifactId>podam</artifactId>
<version>[latest.version]</version>
<!-- <scope>test</scope> -->
</dependency>
- 如果您不想使用默认值(随机数据),请定义
DataProviderStrategy
- 定义
PodamFactory
bean,使用数据提供者策略 初始化
- 在代码中使用
PodamFactory
bean - Define your
DataProviderStrategy
if you don't want the default (Random data) - Define
PodamFactory
bean, initialized with the Data Provider Strategy - Use the
PodamFactory
bean in your code
PodamFactory factory = new PodamFactoryImpl();
MyPojo myPojo = factory.manufacturePojo(MyPojo .class);
// write it as json
System.out.println(new ObjectMapper().writeValueAsString(myPojo));
这篇关于如何在不创建对象的情况下将Java类转换为json格式结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!