繁体   English   中英

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

[英]How do I convert Json object to a Java object dynamically

这是我的用例:

我在服务器端有这些类。

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"
}

@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 {
    // ...
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM