【问题标题】:Spring: Nested object does not get deserializedSpring:嵌套对象不会反序列化
【发布时间】:2021-03-29 22:59:36
【问题描述】:

我正在将 POST 请求从 angular 发送到 spring。它的反序列化大部分是正确的,但是一个嵌套对象被反序列化为一个空对象。

我的 Angular 界面如下所示:

// ClientMedicalModal.ts
export interface ClientMedicalModal {
  clientMedicalId: number;
  client: ClientModel;
  medicalEvidence: MedicalEvidence;
}

// ClientModal.ts
export interface ClientModal {
  clientId: number;
}

// MedicalEvidenceModal.ts
export interface MedicalEvidenceModal {
  B001: string;
  B003: string;
  B004: string;
}

我的 Java 对象如下所示:

public class ClientMedical implements Serializable {
  private Integer clientMedicalId;
  private Client client;
  private MedicalEvidence medicalEvidence;

  // getter and setter
}

public class Client implements Serializable {
  private Integer clientId;

  // getter and setter
}

public class MedicalEvidence implements Serializable {
  private String B001;
  private String B003;
  private String B004;
  
  public String getB001() {
    return B001;
  }

  public MedicalEvidence setB001(String b001) {
    B001 = b001;
  }
  // all other getter and setter
}

当我从浏览器查看帖子消息时,一切似乎都正常: {"medicalEvidence":{"B001":"Test","B003":"TestMessage","B004":"Whatever"},"client":{"clientId":1}}

在 Spring 中调试我收到请求,有一个 clientId = 1 的 Client-Object,但 ClientEvidence-Object 为空,所有 B00* 字段均为空。 See here the debugging values

Spring 表单绑定将表单参数绑定到 Client 类的各个字段,但是 MedicalEvidence 是空白的,因此 Spring 实例化了一个新的 MedicalEvidence 类,其中所有字段都具有空值。为什么参数没有绑定到 MedicalEvidence 的类字段,而是绑定到 Client 的类(以及我使用相同方式的所有其他类)?顺便提一句。如果我只是从 Angular 发送 MedicalEvidence,它也不起作用。对象参数仍然是空的。

【问题讨论】:

    标签: java json angular


    【解决方案1】:

    尝试使用 b001、b002、.. 作为名称,在您的用例中第一个字母不应大写,除非您想使用一些注释。并使用“这个”。在 setter 方法中。

    public class MedicalEvidence implements Serializable {
      private String b001;
      private String b003;
      private String b004;
                     ^^^^
      
      public String getB001() {
        return b001;
      }
    
      public MedicalEvidence setB001(String b001) {
        this.b001 = b001;
        ^^^^^
      }
    

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2018-09-21
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多