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

本小妞迷上赌 提交于 2020-06-16 08:54:10

问题


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

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.

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:

 {"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.


回答1:


You could use 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.

Add PODAM dependency in your project

<dependency>
  <groupId>uk.co.jemos.podam</groupId>
  <artifactId>podam</artifactId>
  <version>[latest.version]</version>
  <!-- <scope>test</scope> -->
</dependency>
  • 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));


来源:https://stackoverflow.com/questions/58831892/how-to-convert-java-class-to-json-format-structure-without-creating-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!