8

How to include class name in all serialized objects? E.g. adding "_class: 'MyClass'" to output value. Is there some global setting for that? I don't want to add any annotation to pojo classes.

I'm using it with spring4 webmvc @ResponseBody (only json format).

  • Spring uses Jackson by default, so check the Jackson project: https://github.com/FasterXML/jackson-databind I couldn't find anything at first glance though – Sean Patrick Floyd Jun 27 '14 at 14:09

1 Answers1

10

You need to annotated your type with the @JsonTypeInfo annotation and configure how the type information should be serialized. Refer this page for 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'}
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48