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

标签 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
}

我有一个接受操作的 Controller 。我希望根据客户端发送的内容正确分配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 {
    // ...
 }

关于java - 如何动态地将Json对象转换为Java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42104774/

相关文章:

java - 尝试连接到 Java DB netbeans 中的数据库?

android - JSON - 与 Android 应用程序一起使用的单个文件

ios - 如何在 Swift 中从 JSON 解析值大于 2147483647 的 Int

java - 无法更新 java.security 文件 - 想要添加 bouncy caSTLe 提供程序

java - 当我用两个分号结束一行时,编译器不会提示。为什么?

java - 从kafka消息中获取主题

java - 返回不同类型的对象时,将访问者或监听器与 ANTLR4 一起使用

json - 如何在 Github Wiki 中设置 JSON block 的样式?

php - 删除php中仅一个json键值对中的多余反斜杠

javascript - 如何正确加载 URL 并访问其内容