I am pretty new to Java and I got a requirement of converting Strings to a json structure. My below codes works fine but I have to create multiple objects and my code looks bit ugly. I want to know the better approach.
I want the below Json Structure from three Strings SourceApplication, messagType and payload
Required Json Structure
{
"request": {
"header": {
"sourceApplication": "SomeString"
"messageType": "SomeString"
},
"body": {
"payload": "SomeString"
}
}
}
Below is my code.
POJO Class (For mapping)
package com.test.transformer;
import java.io.Serializable;
public class JsonMapper implements Serializable {
private Request request;
public Request getRequest ()
{
return request;
}
public void setRequest (Request request)
{
this.request = request;
}
public static class Request implements Serializable{
private Body body;
private Header header;
public Body getBody ()
{
return body;
}
public void setBody (Body body)
{
this.body = body;
}
public Header getHeader ()
{
return header;
}
public void setHeader (Header header)
{
this.header = header;
}
}
public static class Header implements Serializable{
private String sourceApplication;
private String messageType;
public String getSourceApplication ()
{
return sourceApplication;
}
public void setSourceApplication (String sourceApplication)
{
this.sourceApplication = sourceApplication;
}
public String getMessageType ()
{
return messageType;
}
public void setMessageType (String messageType)
{
this.messageType = messageType;
}
}
public static class Body implements Serializable{
private String payload;
public String getPayload ()
{
return payload;
}
public void setPayload (String payload)
{
this.payload = payload;
}
}
}
My Main Class
package com.test.transformer;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
public class JsonTest {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String srcApp = "TestSrc";
String msgType = "msgtype";
String payload = "mainMsg";
JsonMapper.Header h = new JsonMapper.Header();
JsonMapper.Body b = new JsonMapper.Body();
JsonMapper.Request r = new JsonMapper.Request();
h.setSourceApplication(srcApp);
h.setMessageType(msgType);
b.setPayload(payload);
r.setHeader(h);
r.setBody(b);
JsonMapper j = new JsonMapper();
j.setRequest(r);
String jsonInString = null;
try {
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(j);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(jsonInString);
}
}