Home > Software engineering >  RequestBody handling a JSON containing Strings and a List
RequestBody handling a JSON containing Strings and a List

Time:11-16

I'm sending a post request from the client to the server. The body of the post request looks like this:

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

while the "setDataList()" returns the following structure: [ {…}, {…}, {…}, ..., {…} ]

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

I'm having issues processing the content of the "dataFields" key at the server. Currently, the SpringBoot applicaiton looks like this:

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

and "ManageRequest" like this:

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

}

I'm not experienced in handling such requests with Java. My goal would be to extract the content of the "dataFields" like this: "dataFields[0], dataFields[1], ..." and allocate them to a new List to add to a post request. At the moment, the list seems to be empty when arriving at the end point.

CodePudding user response:

Your problems is with the List. The server is waiting for a List of Strings but you are sending a List of objects with fields that are Strings.

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

You should create a class DataField and it would looks like this

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

}

And then in your ManageRequest class you should do like this:

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

    //Getter and setters
}


  • Related