I have used Jackson and JSONObject to generate a plain JSON - things are fine here. I have a specific case where my pojo looks like below and i need the JSON is the specified format.
package test;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "login")
public class LoginApi implements IRestBean {
private String username;
private String password;
private String sfSessionId;
private String sfServerUrl;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSfSessionId() {
return sfSessionId;
}
public void setSfSessionId(String sfSessionId) {
this.sfSessionId = sfSessionId;
}
public String getSfServerUrl() {
return sfServerUrl;
}
public void setSfServerUrl(String sfServerUrl) {
this.sfServerUrl = sfServerUrl;
}
}
The JSON that i am able to generate looks like this:
{
"username" : null,
"password" : null,
"sfSessionId" : null,
"sfServerUrl" : null
}
But this is not my requirement - i need the JSON in the below format so that my server accepts this as a valid JSON:
{
"@type":"login",
"username":"username@domain.com",
"password":"password",
"sfSessionId":null,
"sfServerUrl":null
}
Please help. Thanks in advance!
Change the IRestBean
interface to include the @JsonTypeInfo
annotation:
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="@type")
public interface IRestBean {
...
}
Next, annotate the LoginApi
class with @JsonTypeName
:
@XmlRootElement(name = "login")
@JsonTypeName("login")
public class LoginApi implements IRestBean {
...
}
These are both Jackson-specific annotations.