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.
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>
DataProviderStrategy
if you don't want the default (Random data)PodamFactory
bean, initialized with the Data Provider StrategyPodamFactory
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));