使用json4s

时间:2017-12-19 05:28:31

标签: json scala java-time json4s

如何解析YYYY-MM-ddjava.time.LocalDate的字符串?目前我尝试了以下方法:

  1. 导入JavaTimeSerializers
  2.   

    抛出错误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 }
    
    1. 覆盖DefaultFormats
    2.   

      抛出错误发现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 }
      
      1. 尝试根据此处的示例定义CustomFormatter
      2.   

        错误预期类型是:(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
        

1 个答案:

答案 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