0

I am trying to make a rest api call but keeps getting 400 Bad Request. From the logs, it seems that there is a problem with one of the LocalDate fields of my POJO.

My POJO:

public class MyObj implements Serializable {
private Long id;
private String remark;
private LocalDate someDate;
...other fields, getter and setter

In my main()

MyObj myObj = new MyObj();
myObj .setRemark("My test case");
myObj .setSomeDate( LocalDate.now());
...

 WebResource webResource = client
                .resource("my_url");

        webResource
                .header("apikey", "mykey")
                .accept("application/json")
                .type("application/json")
                .post(MyObj.class, myObj );

Running the above code I get the following error: Bad Request: JSON parse error: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string. at [Source: (PushbackInputStream); line: 1, column: 159] (through reference chain: com.xxx.MyObj["someDate"])

Any idea why the above happened?

xcoder
  • 1,336
  • 2
  • 17
  • 44
  • as the error says expected array or string and what you are passing is a LocaleDate object in your POJO make it a String and in the code level may be have a LocaleDate object for the same and use toString(). – Shubham Jun 06 '19 at 12:07
  • Can you add the JSON structure produced by `my_url` to your question? Jackson expects the format to be `[2019, 6, 6]` or `"2019-06-06"` if I'm not mistaken, and I assume that your REST service isn't doing that. – g00glen00b Jun 06 '19 at 12:35

2 Answers2

2

LocalDate should be converted to string on serialization and converted back to LocalDate on deserialization. For that purpose you can use @JsonDeserialize and @JsonSerialize on object LocalDate property(ies)

@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate someDate;

For more information refer to this link: https://kodejava.org/how-to-format-localdate-object-using-jackson

Another way is to use ObjectMapper and to register modul JavaTimeModule()

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

Example of using ObjectMapper and similar problem: https://groups.google.com/forum/#!topic/jackson-user/XdHvRKG1vhY

frenky
  • 76
  • 1
  • 6
0

You need to annotate your LocalDate to tell how it should be converted to String. Here is a snippet for ZonedDateTime, but all you will need to do is change mask to fit LocalDate.

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
public ZonedDateTime getTime() {
    return time;
}

Here is the link to the original question: Spring Data JPA - ZonedDateTime format for json serialization

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36