3

I have two fields: startDate and endDate and I need to make sure the end date is equal to or later than the start date. What's the best way to do this?

I would like to ensure that endDate is deserialized after startDate so I can put the logic in its setter method like:

@JsonSetter( "end" )
public void setEnd(String end)
{
    this.endDate = parseZonedDateTime( end );

    //invalid
    if ( this.endDate.compareTo( this.startDate ) < 0 )
    {
        //Throw a validation exception
    }
}

But that only works if start is guaranteed to be set first.

best wishes
  • 4,426
  • 1
  • 30
  • 49
Don Rhummy
  • 22,590
  • 37
  • 154
  • 291
  • why not write a custom deserializer? – best wishes Mar 26 '18 at 03:09
  • 1
    Possible duplicate of [Jackson ObjectMapper - specify serialization order of object properties](https://stackoverflow.com/questions/27577701/jackson-objectmapper-specify-serialization-order-of-object-properties) – Alexander Polozov Mar 26 '18 at 03:19
  • 1
    Add a constructor that takes all your fields and do validation there. See [this question](https://stackoverflow.com/questions/21920367/why-when-a-constructor-is-annotated-with-jsoncreator-its-arguments-must-be-ann) for notes on constructor annotation. – teppic Mar 26 '18 at 03:27
  • May not be a clean solution but kind of a hack is to put a placeholder and inject or replace it at the end ? – royalghost Mar 26 '18 at 03:40
  • 2
    @AlexanderPolozov that's serialization, not deserialization – Don Rhummy Mar 26 '18 at 16:56

1 Answers1

1

I have two fields: startDate and endDate and I need to make sure the end date is equal to or later than the start date. What's the best way to do this?

I would not try to do this by jackson. Jackson should only focus on converting json to object. The valid of values should be taken care of by jackson. Nor the deserialization order.

Try validating after jackson's converting, either manually or by validation framework like JSR-303.

John
  • 1,524
  • 1
  • 12
  • 20