简体   繁体   中英

Use Circe to decode Normal Class (not case class)

I have written this code to read and write josn using circe

import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
case class Foo(i: Int)
val f = Foo(10)
val json = f.asJson.toString
val t1 = decode[Foo](json)

this works very well. But if I create a normal class Bar

class Bar { var i : Int = 0 }
decode[Bar](json)

Now I get error

 could not find implicit value for evidence parameter of type io.circe.Decoder[$sess.cmd25.Bar]

So is it possible to work with normal classes and decode them from json using Circe?

With io.circe.generic.auto._ , you're using Circe's automatic generic derivation, which is backed by Shapeless's LabelledGeneric typeclass. LabelledGeneric only works with product types like tuples and case classes. That's why your seeing this error, because Circe's auto mode could not automatically derive a Decoder instance for your plain class. What you can do is manually implement a decoder for your class (see custom encoders/decoders part).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM