Decoding: Configuration.default.withDefaults makes it use the default value when the decoding the field failed
See original GitHub issueI’m using the Configuration.default.withDefaults feature and lots of my case classes have defaults values for members. However, when decoding a json where there is an error (e.g. type mismatch) it uses the default value and swallows the error:
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.auto._
implicit val customConfig: Configuration = Configuration.default.withDefaults
final case class Foo(number: Int = 999)
io.circe.parser.decode[Foo]("""{"number": "not a number!"}""")
res0: Either[io.circe.Error,Foo] = Right(Foo(999))
Ideally, I’d like the default value to be used only if the field was missing from the json, and get an error when it was there but incorrectly.
Can I change this behavior somewhere central so that I don’t need to have custom decoders for all my case classes with defaults?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:7
- Comments:7 (6 by maintainers)
Top Results From Across the Web
Use default fields in case class when decoding/encoding json ...
You can do this using the circe-generic-extras package. It's a separate dependency you have to put in your build. For sbt, that's:
Read more >circe/circe - Gitter
how do I decode case class FooField(value: String). to have value of field named foo if one is present, otherwise have decoding failure....
Read more >io.circe.generic.extras.Configuration Scala Example
fromFile(file) val raw = try { src.mkString } finally { src.close() } implicit val config = Configuration.default.withDefaults decode[List[ABI]](raw) } }.
Read more >Encoding and decoding - circe
circe uses Encoder and Decoder type classes for encoding and decoding. An Encoder[A] instance provides a function that will convert any A to...
Read more >12. OAuth2 - Spring
This section shows how to configure the OAuth 2.0 Login sample using Google ... Therefore, it makes sense to provide default values in...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I think that “fallback to default value if decoding failed” is a good option to have. But it should not be default, since I think
I think popular JSON-based Web-APIs works like this.
Took the time to try the ApplicativeError idea it out and found it was more complicated than helpful. But finished the pull request anyway while doing so. 😉 Please have a look.