Home > Mobile >  How can I add many objects as a JsonArray using one POST request
How can I add many objects as a JsonArray using one POST request

Time:09-30

I'm trying to add multiple objects using one POST request to my API. I have read some possible solutions to this problem one was to include the parameter List yourObjectList on the method that I have created to receive that request. and then I can send multiple "Objects" inside that request as JSON ex:

[
    {
        
        "prop1": "value1",
        "prop2": "value2"
    },
    {
        
        "prop1": "value3",
        "prop2": "value4"
    }
]

the problem is when I do that all my Object getters are throwing errors "Cannot resolve method 'myGetter' in 'List' ".

What should I do to make this work ?

myDTO:

@NoArgsConstructor
public class InvoiceDTO {

  @NotNull(message = "PersonId can't be null")
  @PersonId
  private String personId;

  @NotNull(message = "invoiceDate can't be null")
  // @DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd"))
  @PastOrPresent
  @JsonFormat(pattern = "yyyy-MM-dd")
  private LocalDate invoiceDate;

  @NotNull(message = "invoiceNumber can't be null")
  private String invoiceNumber;

  @NotNull(message = "phone number can't be null")
  private Long phoneNumber;

  @NotNull(message = "invoiceAmount can't be null")
  private Double invoiceAmount; //how much does the client ows the org

  @NotNull(message = "invoiceNumber can't be null")
  private String accountNumber;

  private int msdin; //Type of subscription
}

CodePudding user response:

A Json object can contain a list of objects but I’m pretty sure that a list as you’ve written is not a valid JSON object. So, a valid JSON object will always be in between {}

If your rest endpoint is expecting an object of type List then try with

{
  [
      {
          
          "prop1": "value1",
          "prop2": "value2"
      },
      {
          
          "prop1": "value3",
          "prop2": "value4"
      }
  ]
}

If your endpoint is expecting an object that contains a List (a better option since an object can be easily modified to contain various things, additional parameters a side from the list) then try:

{
  "myList":[
      {
          
          "prop1": "value1",
          "prop2": "value2"
      },
      {
          
          "prop1": "value3",
          "prop2": "value4"
      }
  ]
}

CodePudding user response:

I had to make the object passed to the method of type List. Then I had to figure out a way to loop through this list, so I used for loop, ex:

for (InvoiceDTO invoices : invoiceDTO) {
//your code
}

Now, problem is solved.

  • Related