0

in my crud application a post api receives the following body

@Data
@AllArgsConstructor
@NoArgsConstructor
public class BodyRequest {

    private String description;
    private List<Request> ListRequest; 
}

when listRequest is not passed in the body of the request it becomes null is there any way to set an empty value for the listRequest list when it is null? I would like to know if there is the possibility to add an annotation on the list that allows such modification as @ value or @json

I tried to add @JsonDeserialize (using = OptimizedListDeserializer.class) to the list and to define the OptimizedListDeserializer class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class BodyRequest {

    private String description;
    @JsonDeserialize (using = OptimizedListDeserializer.class)
    private List<Request> ListRequest; 
}

public class OptimizedListDeserializer extends StdDeserializer<List<Request> > {


    protected OptimizedListDeserializer(StdDeserializer<?> src) {
        super(src);
        // TODO Auto-generated constructor stub
    }

    @Override
    public List<Request>  deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException {
           return new ArrayList<>();
    }
}

but when i try to call the service i get

"code": 415,
"error": "Content type 'application/json;charset=UTF-8' not supported"
4
  • 6
    Make a noArgs constructor yourself, and initialise it. Commented Apr 8, 2020 at 10:09
  • 3
    Or initialize it inline. Commented Apr 8, 2020 at 10:10
  • Maybe you want to build your own deserializer baeldung.com/jackson-deserialization Commented Apr 8, 2020 at 10:19
  • @Robertiano They definitely don't want to do that. Commented Apr 8, 2020 at 10:19

2 Answers 2

1

the simplest way to do that is initialize the list in the class like this

@Data
@AllArgsConstructor
@NoArgsConstructor
public class BodyRequest {

    private String description;
    private List<Request> ListRequest = new ArrayList(); 
}
Sign up to request clarification or add additional context in comments.

Comments

0

As of jackson 2.9 you got this : @JsonSetter(nulls = Nulls.AS_EMPTY) public void setStrings(List<String> strings) { this.strings = strings; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.