Spring Boot 处理包含字符串和列表的JSON的RequestBody

zzlelutf  于 2022-11-23  发布在  Spring
关注(0)|答案(1)|浏览(180)

我从客户端向服务器发送一个post请求。post请求的正文如下所示:

...
        body: JSON.stringify
            ({
                command: 'someString',
                dataFields: setDataList()
            })
        ...

而“setDataList()”返回以下结构:【{...},{...},{...},...,{...}】

[0: {type: "_header_", label: "upload"}
        1: {type: "_image_", name: "data:image/jpeg;base64", value: "base64 encoded string", label: "someImage.JPG"}
        2: {...}]

我在服务器上处理“dataFields”键的内容时遇到问题。当前,SpringBoot应用程序如下所示:

@PostMapping(
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public void postBody(@RequestBody ManageRequest manageRequest) {
  ...
}

和“管理请求”,如下所示:

import java.util.List;

public class ManageRequest {
  private String accountId;
  private String command;
  private String transactionId;
  private List<String> dataFields;

  public String getAccountId() {
    return accountId;
  }

  public String getTransactionId() {
    return transactionId;
  }

  public void setTransactionId(String transactionId) {
    this.transactionId = transactionId;
  }

  public void setAccountId(String accountId) {
    this.accountId = accountId;
  }

  public String getCommand() {
    return command;
  }

  public void setCommand(String command) {
    this.command = command;
  }

  public List<String> getDataFieldList() {
    return dataFields;
  }

  public void setDataFieldList(List<String> dataList) {
    this.dataFields = dataList;
  }

}
我没有使用Java处理此类请求的经验。我的目标是提取“dataFields”的内容,如下所示:“dataFields[0],dataFields[1],...”,并将其分配到一个新的List中,以添加到post请求中。此时,到达终点时,该列表似乎是空的。

cigdeys3

cigdeys31#

您的问题出在清单上。服务器正在等候字串清单,但您传送的是含有字串字段的对象清单。

private List<String> dataFields; // This property is a List of string not a list of "dataFields"

您应该创建一个DataField类,它看起来如下所示

public class DataField{
    
    private String type;
    private String label;
    private String name;
    .
    .
    .

}

然后在ManageRequest类中,您应该执行以下操作:

public class ManageRequest {
    private String accountId;
    private String command;
    private String transactionId;
    private List<DataField> dataFields;

    //Getter and setters
}

相关问题