3

What can be done, if street is null? I will get an exception in the HTTP POST. NotNull is checking if property is null or not...

@NotNull
@Column(name = "street")
@JsonIgnore
private String street;

In this case JsonIgnore is not working. Why? I thought, if I use JsonIgnore not null would not be checked....

Can I overload @NotNull with @JsonIgnore or some other annotation?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
  • Could you specify better ? – Vitorlui Sep 01 '16 at 13:07
  • Could you describe little bit more ? – P S M Sep 01 '16 at 13:09
  • 1
    Basically, you should not return the entity to http POST response. If it is null hibernate will throw an exception that you should handle gracefully and then setting the property to null in DTO will simply remove that tag from the response. Hope this helps. – MDaniyal Sep 01 '16 at 13:11
  • Do you want to Ignore this field only if is null the value? – Vitorlui Sep 01 '16 at 13:21
  • 2
    NotNull - is a JSR-303 bean validation annotation and JsonIgnore is one of Jackson annotations. They don't know about each other. In your code, you should set a value of this field manually before validation to pass it. What are your purpose and a desirable result (on a business-level)? – Ivan Sep 01 '16 at 13:23
  • 1
    I want to ignore the field if value is null. Is it possible? – Alexander Peinsipp Sep 01 '16 at 13:27
  • Please, check the answer bellow. – Vitorlui Sep 01 '16 at 13:30
  • @AlexanderPeinsipp, it is possible but there are a lot of ways. It all depends on what do you want. Please, clarify in a nutshell. Suppose, there are no NotNull and JsonIgnore annotations. What becomes wrong? Why do you use JsonIgnore? Is it for hiding street in output (when it is filled) or for ignoring street on input (from a request)? For different validation strategies you can use validation groups but I am not sure that is what you really need. – Ivan Sep 01 '16 at 14:18

1 Answers1

1

If you want to "ignore" null values you can use:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

from: How to tell Jackson to ignore a field during serialization if its value is null?

Why JsonIgnore with NotNull doesnt work?

Basically the JSonIgnore annotation has not relationship with Not Null because the first is Jackson and the other is JPA.

I believe these topics can help you:

Serializing JPA entities to JSON using Jackson

Confusion: @NotNull vs @Column(nullable = false)

http://www.davismol.net/2015/03/10/jackson-json-difference-between-jsonignore-and-jsonignoreproperties-annotations/

Community
  • 1
  • 1
Vitorlui
  • 760
  • 1
  • 11
  • 26