Created
          July 20, 2018 00:33 
        
      - 
      
 - 
        
Save alexanderfefelov/af4cbc67b30063f32a81893e07c78287 to your computer and use it in GitHub Desktop.  
    Decode Joda DateTime with circe
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import io.circe.generic.auto._ | |
| import io.circe._ | |
| import io.circe.parser._ | |
| import org.joda.time.DateTime | |
| import org.joda.time.format.DateTimeFormat | |
| import scala.util.control.NonFatal | |
| object CirceDateTimeDecoder extends App { | |
| val dateFormatter = DateTimeFormat.forPattern("yyyyMMdd") | |
| implicit val decodeDateTime: Decoder[DateTime] = Decoder.decodeString.emap { s => | |
| try { | |
| Right(DateTime.parse(s, dateFormatter)) | |
| } catch { | |
| case NonFatal(e) => Left(e.getMessage) | |
| } | |
| } | |
| case class Model(date: DateTime) | |
| val str = """{"date": "20180101"}""" | |
| val data: Either[Error, Model] = decode[Model](str) | |
| data match { | |
| case Right(model) => println(model) | |
| case Left(e) => System.err.println(e) | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment