0

I have a little todo app with an Angular frontend and Spring Boot as backend. I'm very new to Spring Boot and might need a further explanation. Thanks for your understanding.

My problem is to parse the date format I get from the angular datepicker component to type Date. This is the current error I'm getting:

"JSON parse error: Cannot deserialize instance of `java.util.Date` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.Date` out of START_OBJECT token
        at[Source:(PushbackInputStream);line:1,column:73](through reference chain:todo.ToDo["dueDate"])"

I have looked for a solution and I think I found one but I do not quite understand how to implement it in my situation: Angular2 Spring boot date serialization

As I'm currently receiving the post from the user as a ToDo entity:

@PostMapping("/todos")
    ToDo newToDo(@RequestBody ToDo newToDo) {
        return repository.save(newToDo);
    }

How should I extract the date input by the user? I would then parse the date and after that save it. In my head it should work then...

Thanks for any help or suggestions

2
  • 1
    FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle. Commented Jan 27, 2019 at 20:59
  • show the @ RequestBody and JSON Commented Jan 28, 2019 at 3:24

1 Answer 1

1

You may need to use LocalDateSerializer and LocalDateDeserializer for this.

ToDo class.

 public class ToDo {
  @JsonDeserialize(using = LocalDateDeserializer.class)
  @JsonSerialize(using = LocalDateSerializer.class)
  private LocalDate dueDate;

  // getters and setters

 }

LocalDateDeserializer.java

   import java.time.LocalDate;

   import com.fasterxml.jackson.core.JsonParser;
   import com.fasterxml.jackson.databind.DeserializationContext;
   import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

  public class LocalDateDeserializer extends StdDeserializer<LocalDate> {

private static final long serialVersionUID = 1L;

protected LocalDateDeserializer() {
    super( LocalDate.class );
}

@Override
  public LocalDate deserialize( JsonParser jp, DeserializationContext ctxt ) {
    try {
        return LocalDate.parse( jp.readValueAs( String.class ) );
    }
    catch (Exception e) {
        // TODO: handle exception
        return null;
    }
}
}

LocalDateSerializer.java

 import java.io.IOException;
 import java.time.LocalDate;
 import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class LocalDateSerializer extends StdSerializer<LocalDate>
{

private static final long serialVersionUID = 1L;

public LocalDateSerializer()
{
    super( LocalDate.class );
}

  @Override
  public void serialize( LocalDate value, JsonGenerator gen, SerializerProvider sp ) 
  throws IOException, JsonProcessingException
    {
        gen.writeString( value.format( DateTimeFormatter.ISO_LOCAL_DATE ) );
  }
}

And also you should pass date as a string Ex: "2019-02-01". Passing Date object from the front-end is not a good practice.

    import { Component,Input } from '@angular/core';
   import {TodoService} from './todo.service';

@Component({
  selector: 'app-root',
   templateUrl: './app.component.html', 
  styleUrls: ['./app.component.scss']
 })
  export class AppComponent {
  title = 'ToDoApp';

constructor(private todoService: TodoService) {
}

@Input() toDoData = {name: '', dueDate: Date};

addToDo() {
    this.toDoData.dueDate = // formatted date
    this.todoService.addToDo(this.toDoData).subscribe((result) => {
        this.todoService.addToDo(this.toDoData);
        console.log(this.toDoData.dueDate);
    });
}

convertToMilliseconds(dueDate: DateConstructor) {
    return dueDate.valueOf();
}
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help, I've created the two classes you suggested. I do not get an error when I create a new todo on the UI but the date value is null. My ToDo class file: pastebin.com/gUKYyCEE
Sure, thanks for helping me out! todo.service.ts: pastebin.com/NXeC4xj5 app.component.ts: pastebin.com/bMqe39XD html: pastebin.com/EQC9asPq
see my modified answer. I have tested this and verified :)

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.