0

I have the following endpoint

@PutMapping
ResponseEntity<MyObject> updateMyObject(@ModelAttribute MyObjectDTO myObjectDTO) {
    ...
}

And my DTO is

@Value
class MyObjetDTO {
    ...
    List<ChildDTO> children;
}

And my child DTO is

@Value
class ChildDTO {
    ...
    Long id;
    String name;
}

In the UI, I send the request using form data (I need to do this since I have a multipart field in my DTO):

const formData = new FormData();
...
formData.append("children", JSON.stringify([]));
axios.put("http://localhost:8080/api, formData, {})...

I got this error on backend:

Failed to convert value of tyoe "java.lang.String" to required type "java.lang.List"

iPhoneJavaDev
  • 821
  • 5
  • 33
  • 78

1 Answers1

2

Your Spring Controller is waiting for information received as form data.

When Spring tries to build the backend object MyObjectDTO from the information provided in the submitted HTTP request with your axios call, it expects children to be a property of type List as your defined it:

List<ChildDTO> children;

But instead you are providing a String, [], in your form data:

formData.append("children", JSON.stringify([]));

If you want to pass an empty value for the children property, please, instead don't pass any value for it.

If you need to pass a value for say a list of two children, you need to index then, and pass that information to your Controller, something like:

formData.append("children[0].id", "3");
formData.append("children[0].name", "a name");
formData.append("children[1].id", "5");
formData.append("children[1].name", "another name");

As an alternative, as suggested as well by @ozkanpakdil in his comment and linked question, please, consider serializing your entire form to JSON format and use @RequestBody in your Controller instead.

jccampanero
  • 50,989
  • 3
  • 20
  • 49