json - include class name in all objects serialized by jackson -
how include class name in serialized objects? e.g. adding "_class: 'myclass'" output value. there global setting that? don't want add annotation pojo classes.
i'm using spring4 webmvc @responsebody (only json format).
you need annotated type @jsontypeinfo
annotation , configure how type information should serialized. refer this page reference.
example:
public class jacksonclassinfo { @jsontypeinfo(use = jsontypeinfo.id.class, property = "__class") public static class bean { public final string field; @jsoncreator public bean(@jsonproperty("field") string field) { this.field = field; } @override public string tostring() { return "bean{" + "field='" + field + '\'' + '}'; } } public static void main(string[] args) throws ioexception { bean bean = new bean("value"); objectmapper mapper = new objectmapper(); string json = mapper.writerwithdefaultprettyprinter().writevalueasstring(bean); system.out.println(json); system.out.println(mapper.readvalue(json, bean.class)); } }
output:
{ "__class" : "stackoverflow.jacksonclassinfo$bean", "field" : "value" } bean{field='value'}
Comments
Post a Comment