如何动态地将Json对象转换为Java对象

时间:2017-02-08 04:32:33

标签: java json

这是我的用例:

我在服务器端有这些课程。

class Individual {
  protected String uri;
  protected int id;
}

class Person extends Individual {
  // Person properties like names, address etc
  String type = "Person";
}

class Role extends Individual {
  // Role properties like name, title etc
  String type = "Role";
}

class Organization extends Individual {
  // Org properties like name name, address etc
  String type = "Organization";
}

我的课程如下Action

class Action {
  String performedBy; // This can be any Individual
}

我有一个接受Action的控制器。我希望根据客户端发送的内容正确分配Individual。我的Action&定义其他类来实现这个目标吗?

如果我发送以下内容,我希望performedBy成为Person

{
 "id": 10,
 "uri":"uri_blah",
 "lastname": "last_name",
 "type":"Person"
}

1 个答案:

答案 0 :(得分:3)

@JsonType注释,允许将类型序列化为属性:

@JsonTypeInfo(
   use = JsonTypeInfo.Id.NAME, 
   include = JsonTypeInfo.As.PROPERTY, 
   property = "type")
@JsonSubTypes({ 
   @Type(value = Person.class, name = "Person"), 
   @Type(value = Role.class, name = "Role") 
   // ...
 })
 public abstract class Individual {
    // ...
 }