Reputation: 1925
I have a bean class like
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDate;
public class Form {
private String name;
private Long numID;
private String Address;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate date1;
// getters and setters
}
This is used in a rest controller class
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
public class MyController {
private String MY_URL = "/model.do"
@RequestMapping(value = {MY_URL}, method = RequestMethod.POST)
@ResponseBody
Public Model getModelType(@ModelAttribute Form myForm){
}
}
now when I pass a arabic date object which is encoded like
%D9%A2%D9%A0%D9%A1%D9%A9-%D9%A0%D9%A4-%D9%A1%D9%A5, the conversion is failing with the below error
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'form' on field 'date1': rejected value [????-??-??]; codes [typeMismatch.form.date1,typeMismatch.isoCheckInDate,typeMismatch.java.time.LocalDate,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [form.isoCheckInDate,isoCheckInDate]; arguments []; default message [isoCheckInDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'date1'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDate] for value '????-??-??'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [????-??-??]]
Any idea how can to handle this type of scenario ?
Upvotes: 0
Views: 283
Reputation: 86286
While I don’t know what Spring Framework has done and why, I can show you how to parse your string in plain Java:
DecimalStyle defaultDecimalStyle
= DateTimeFormatter.ISO_LOCAL_DATE.getDecimalStyle();
DateTimeFormatter arabicDateFormatter = DateTimeFormatter.ISO_LOCAL_DATE
.withDecimalStyle(defaultDecimalStyle.withZeroDigit('\u0660'));
String encodedArabicDateStr = "%D9%A2%D9%A0%D9%A1%D9%A9-%D9%A0%D9%A4-%D9%A1%D9%A5";
String arabicDateStr
= URLDecoder.decode(encodedArabicDateStr, StandardCharsets.UTF_8);
LocalDate date = LocalDate.parse(arabicDateStr, arabicDateFormatter);
System.out.println("Parsed date: " + date);
Output from this snippet is:
Parsed date: 2019-04-15
The only trick is to tell the formatter to parse Arabic digits. When we tell it the zero digit (٠
or '\u0660'
), it figures out the other digits.
Upvotes: 2