我有一个返回标记接口的休息服务,这个接口有多个实现,并且在实现中没有任何公共属性.
@RequestMapping(value = "/users/{userName}", method = RequestMethod.GET) public User getUser(@PathVariable("userName") String userName) { return userService.getUser(userName); }
用户及其实现.注意:用户是标记界面.
public interface User {} public AdminUser implements User { // some properties & its setters & getters } public SupportUser implements User { // some properties & its setters & getters }
我使用Jackson 1.9.1来序列化和反序列化.
当我达到以上服务时,我的回答低于响应
{}
当我调试它时,我看到用户实现对象已准备好并发送回Jackson进行序列化.但杰克逊正在向浏览器发送空响应.任何人都建议如何在返回类型为标记接口时使用序列化.
使用@JsonTypeInfo
和@JsonSubTypes
反序列化多态类型,在序列化java对象时维护子类型信息并重新创建确切的子类型.
让我们举一个例子,动物是一个接口,它可以是老虎或狮子,它们都扩展了动物界面.在反序列化时,我们想要创建精确的动物类型并演示@JsonTypeInfo和@JsonSubTypes注释的使用.
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="name") @JsonSubTypes({ @JsonSubTypes.Type(value=Lion.class, name="lion"), @JsonSubTypes.Type(value=Tiger.class, name="tiger"), }) public interface Animal { } @JsonTypeName("lion") public class Lion implements Animal { private String name; private String roar; //constructor & setters & getters } @JsonTypeName("tiger") public class Tiger implements Animal { private String name; private String purr; //constructor & setters & getters }
主要方法:
Listanimal = new ArrayList (); animal.add(new Lion("lion", "roar")); animal.add(new Tiger("tiger", "purr")); animal.add(new Tiger("tiger", "purrrrrrrrr")); URL url = JacksonPolymorphicSerialization.class.getClassLoader().getResource("animals.json"); File file = new File(url.getPath()); // de-serailization sub types new ObjectMapper().writeValue(file, animal); // serailization animals and its subtype List animals = new ObjectMapper().readValue(file, List.class); System.out.println(animals); output : [{name=lion, roar=roar}, {name=tiger, purr=purr}, {name=tiger, purr=purrrrrrrr}]
希望这有助于您了解使用Jackson对多态类型进行序列化和反序列化.