如何解析YYYY-MM-dd
到java.time.LocalDate
的字符串?目前我尝试了以下方法:
JavaTimeSerializers
抛出错误JString无法转换为LocalDate
case class Dates(createdAt: LocalDate, updatedAt: LocalDate, startDate: LocalDate, endDate: LocalDate )
implicit val formats = defaultFormats ++ org.json4s.ext.JavaTimeSerializers.all
implicit val formats = defaultFormats ++ org.json4s.ext.JavaTimeSerializers.all
val input =
"""
|{
| "createdAt": "1999-12-10",
| "updatedAt": "1999-12-16",
| "startDate": "2000-01-02",
| "endDate": "200-01-16"
|}
""".stripMargin
val result = read[Dates] { input }
DefaultFormats
:抛出错误发现java.time.format.DateTimeFormatter期望java.text.SimpleDateFormat
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd")
}
val input =
"""
|{
| "createdAt": "1999-12-10",
| "updatedAt": "1999-12-16",
| "startDate": "2000-01-02",
| "endDate": "200-01-16"
|}
""".stripMargin
val result = read[Dates] { input }
CustomFormatter
错误预期类型是:(PartialFunction [org.json4s.JValue,java.time.LocalDate],PartialFunction [Any,org.json4s.JValue])
object LocalDateSerializer extends CustomSerializer[LocalDate](
format => (
{
case JString(str) => LocalTime.parse(str)
case JNull => null
}
))
implicit val formats = org.json4s.DefaultFormats ++ new LocalDateSerializer
答案 0 :(得分:4)
对于您的第三个错误,您缺少第二个部分功能,请参阅:
ser: Formats => (PartialFunction[JValue, A], PartialFunction[Any, JValue])
所以你可能想要这样做,比如:
object LocalDateSerializer extends CustomSerializer[LocalDate](format => ({
case JString(str) =>
LocalDate.parse(str)
}, {
case date: LocalDate => JString(date.toString)
}))
由于LocalDate
默认模式为yyyy-MM-dd
,因此"200-01-16"
这不是合法时间,您可能希望将其更改为2000-01-16
。