How to encode scala case class to json with any as parameter type of case class?

924 views Asked by At

I have a scala case class as follows

case class Intro(name : String, quality : Any)

I am using scala circe library for encoding this object to Json. The code which i am using is

import io.circe._
import io.circe.generic.auto._
import io.circe.syntax._

object Example extends App{
      println(Intro("Vikash","something").asJson)    
}

It is giving me following error during compilation.

 could not find implicit value for parameter encoder: io.circe.Encoder[com.xxx.Intro]

If i change the type of case class attribute quality to type String then it works fine.

How to encode case class with Any type in attribute

Thanks

1

There are 1 answers

0
L.Lampart On BEST ANSWER

Your problem is related to the fact that you are using automatic codec generation, which is entirely compile time, so given value of type Any it is virtually impossible to generate codec for it. You should be able to solve this by one of the following things:

  1. Use generic instead of Any, you have to make sure, that there is an instance of Encoder and Decoder type class for the type you are using. Your class should look like this than: case class Intro[T](name: String, quality: T). This way you can use Intro[String], Intro[Int] etc.
  2. Provide your own instance of Encoder/Decoder for the type Any, which would be pretty difficult to achieve and for me is rather bad idea.

If you don't know what type classes are or how implicit resolution works you should first learn about them.