Skip to content

Make @ResponseBody method return type available to message converters [SPR-12811] #17408

@spring-projects-issues

Description

@spring-projects-issues

Miroslav Senaj opened SPR-12811 and commented

In Spring MVC I have following object hierarchy.

@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, 
     include = JsonTypeInfo.As.PROPERTY, 
     property = "type") 
public abstract class ParentClass {
}
@JsonTypeName("foo") 
public class Foo extends ParentClass {
    private String person;
}
@JsonTypeName("bar") 
public class Bar extends ParentClass {
    private String item;
}

ACTUAL:
When I generate response from method as List<ParentClass> it generates JSON without "type" : "foo" or "type" : "bar".

@ResponseBody
public List<ParentClass> method() {
    List<ParentClass> result =  // generate classes foo and bar
    return result;
}
[{ "person" : "John Doe" }, { "item" : "rifle" }]

EXPECTED:
In List<T> response type it should generate "type" as well.

@ResponseBody
public List<ParentClass> method() {
    List<ParentClass> result =  // generate classes foo and bar
    return result;
}
[{ "type" : "foo", "person" : "John Doe" }, { "type" : "bar", "item" : "rifle" }]

TRIVIA:
When I return from @Controller in @ResponseBody object which contains List<ParentClass> as

public class AnotherClass { 
    public List<ParentClass> values; 
}

It generates proper response with proper "type" in it.

@ResponseBody
public AnotherClass method() {
    AnotherClass result =  // generate Another class and list of foo and bar
    return result;
}
{ "values" :[
     { "type" : "foo", "person" : "John Doe" }, 
     { "type" : "bar", "item" : "rifle" } ] 
}

See also stackoverflow issue

What I found so far that in
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter:228
this.objectMapper.writerWithView(serializationView).writeValue(generator, value);

Is serializing data without its type and base on this topic it should have writerWithType in order to write type.


Affects: 4.1.1

Issue Links:

Referenced from: commits 31a5434, 3bff7bd

1 votes, 6 watchers

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions