[英]How to convert java class to json format structure without creating object
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.我需要记录多个微服务 api 调用,所以我有一个问题是如何直接从 java2ABBB1A2F2ED4CDEC2C4 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
}
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. 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.
something like:就像是:
String jsonStruct=SomeUtil.convertPojoToJson(MyPojo.class)
then it should give like:那么它应该像:
{"name":"string","address":[]}
My Try:我的尝试:
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));
}
}
actual o/p:实际操作/操作:
{"name":"aa","address":["a","s"]}
required o/p:所需的o / p:
{"name":"string","address":["string"]}
CONCERN: But I need to create without creating object as in real the pojo is huge and not possible to set all dummy data.关注:但我需要在不创建 object 的情况下创建,因为实际上 pojo 很大,无法设置所有虚拟数据。
PODAM is a lightweight tool to auto-fill Java POJOs with data. PODAM 是一个轻量级的工具,可以用数据自动填充 Java POJO。 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在您的项目中添加 PODAM 依赖项
<dependency>
<groupId>uk.co.jemos.podam</groupId>
<artifactId>podam</artifactId>
<version>[latest.version]</version>
<!-- <scope>test</scope> -->
</dependency>
DataProviderStrategy
if you don't want the default (Random data)如果您不想要默认值(随机数据),请定义您的DataProviderStrategy
PodamFactory
bean, initialized with the Data Provider Strategy定义PodamFactory
bean,使用Data Provider Strategy初始化PodamFactory
bean in your code在您的代码中使用PodamFactory
bean PodamFactory factory = new PodamFactoryImpl();
MyPojo myPojo = factory.manufacturePojo(MyPojo .class);
// write it as json
System.out.println(new ObjectMapper().writeValueAsString(myPojo));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.