Search code examples
scalaserializationspray-json

Spray-Json serialize interface type



using spray-json how can I serialize following class

case class Vegetable(name: String, color: String, seller:ISeller)

here ISeller is a Java Interface. I am new to spray-json an not sure how this can be serialized and deserialized.

I tried this but it gives runtime error

implicit val VegetableFormat = jsonFormat3(Vegetable)

Any pointer here will be great.


Solution

  • You need to define a way to convert to/from JSON for your ISeller object. In addition to code you supplied you need to define formatter for ISeller like the following:

      implicit object ISellerJsonFormat extends RootJsonFormat[ISeller] {
        def write(c: ISeller) = JsNull
    
        def read(value: JsValue) = null
      }
    

    The snippet above just ignores ISeller so vegetable.toJson would produce:

    {"name":"Onion","color":"red","seller":null}
    

    If you want to read/write something more meaningful you can implement more complex logic. See the "Providing JsonFormats for other Types" section in https://github.com/spray/spray-json .