0

I have the following classes

public class RequestResponseWrapper {

    MyDto myDto;

}

public class MyDto {

    private String field1;
    private String field2;
    ....
}

and I have the following controller method:

@RequestMapping(...)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ResponseBody
public RequestResponseWrapper putData(@ModelAttribute RequestResponseWrapper requestResponseWrapper) {
        ....
}

I wrote following binder:

@InitBinder("requestResponseWrapper")
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(MyDto.class, new PropertyEditorSupport() {

            public void setAsText(String name) {
                setValue(StringUtils.isNotBlank(name) ? name : null);
            }
        });
}

Now If I got empty object from client it converts to the following structure:

requestResponseWrapper--
                        myDto--
                               field1 = null
                               field2 = null
                               ....

Expected result:

requestResponseWrapper--
                        myDto = null

How to change my code ?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

0

You should not set the value to null if its null. Just set it to the value you want (name) when your value is not null. I hope this makes sense.

    @InitBinder("requestResponseWrapper")
    public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(MyDto.class, new PropertyEditorSupport() {

                    public void setAsText(String name) {
                            if (StringUtils.isNotBlank(name)) {
                                    setValue(name);
                            }

                    }
            });
    }
zpontikas
  • 5,445
  • 2
  • 37
  • 41
  • I believe that at this case I will see same result – gstackoverflow Jun 23 '15 at 16:40
  • Did you try it? Also when you say it converts it to that structure, how do you read the result. If you convert it to json then depending on the library you use you can set it to ignore certain fields when they are null etc. – zpontikas Jun 24 '15 at 07:51