Update case class from incomplete JSON with Argonaut or Circe

前端 未结 2 2179
自闭症患者
自闭症患者 2021-02-20 05:19

I need to create an updated instance from a case class instance (with any needed DecodeJsons implicitly derived), given an incomplete json (some fields missing). Ho

相关标签:
2条回答
  • 2021-02-20 05:52

    You can generate those implicit val defs / pd with macro annotation on Person (in object Person, for example, and do import Person._ to summon implicits). See this unfinished Simulacrum in scalameta (scala-reflect is fine too, but seems like scalameta can be enough here) for usage examples. Also you have to specify missing default value (42) somewhere, for example, in case class constructor (age: Int = 42, recognition can be done in macro too).

    0 讨论(0)
  • 2021-02-20 05:58

    For the sake of completeness: support for "patching" instances like this has been provided in circe since the 0.2 release:

    import io.circe.jawn.decode, io.circe.generic.auto._
    
    case class Person(name: String, age: Int)
    
    val person = Person("mr complete", 42)
    val incompletePersonJson = """{"name":"mr updated"}"""
    
    val update = decode[Person => Person](incompletePersonJson)
    

    And then:

    scala> println(update.map(_(person)))
    Right(Person(mr updated,42))
    

    My original blog post about this technique uses Argonaut (mostly since I wrote it a couple of months before I started working on circe), and that implementation is available as a library, although I've never published it anywhere.

    0 讨论(0)
提交回复
热议问题