Reputation: 301
serialize in json result? How do I serialize or field the interface in json result. I using com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(obj).
The interface field not showing in json result
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = TranslateEN.class, name = "en"),
@Type(value = TranslatePT.class, name = "pt")
})
public interface ITranslate extends Serializable {
String app = "Anota Ai";
}
@XmlRootElement
public final class TranslatePT implements ITranslate {
private static final long serialVersionUID = 1L;
private static TranslatePT instance;
private TranslatePT() {
super();
}
static {
instance = new TranslatePT();
}
public static TranslatePT getInstance() {
return instance;
}
public final Message message = new Message();
public final Entidade entidade = new Entidade();
final static class Message {
public final String defultError = "Erro inesperado";
}
final static class Login {
public final String forbidden = "Sessão expirada, favor efetuar o login novamente.";
public final String confirmacaoSenha = "A senha não confere com a confirmação de senha. Informe novamente.";
}
final static class Entidade {
public final EntidadeDeletada editada = new EntidadeDeletada();
}
final static class EntidadeDeletada {
public final String sucesso = "{0} editada com sucesso.";
}
}
public class MessageSerialize {
@Test
public void loadHtmlFileTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
TranslatePT instanceTranslate = TranslatePT.getInstance();
String dtoAsString = objectMapper.writeValueAsString(instanceTranslate);
Assert.assertNotNull(dtoAsString);
}
}
//result of serialization
{"type":"pt","message":{"defultError":"Erro inesperado"},"entidade":{"editada":{"sucesso":"{0} editada com sucesso."}}}
Upvotes: 1
Views: 895
Reputation: 22234
As Luciano points out (implicitly) static fields are not serialized by Jackson even if you use appropriate annotations. However, Jackson will by default call all getter methods it finds and put the return values in the JSON with a field name derived from getter name. So if you must serialize a static field app
just put a getter method named getApp
in a class, in this case TranslatePT
:
public String getApp() {
return app;
}
Upvotes: 2
Reputation: 6577
The app
variable in the interface is not an instance field, but a constant. Fields in interfaces are implicitly public static final
.
Constants are associated with the class, they are not part of an instance. Jackson only serializes object instances to JSON and hence won't serialize the statics.
Upvotes: 2