Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spray-json for normal classes (non case) on a List

I'm finding myself in a situation in which I need to serialize into JSON a non case class.

Having a class as:

class MyClass(val name: String) {
  def SaySomething() : String = {
    return "Saying something... "
  }
}

I've created a JsonProtocol for this class:

object MyClassJsonProtocol extends DefaultJsonProtocol {

  implicit object MyClassJsonFormat extends JsonWriter[MyClass] {
  override def write(obj: MyClass): JsValue =
    JsObject(
      "name" -> JsString(obj.name)
    )
  }
}

Later on in the code I import the protocol..

val aListOfMyClasses = List[MyClass]() ... // lets assume that has items and not an empty list
import spray.json._
import MyClassJsonProtocol._

val json = aListOfMyClasses.toJson

When trying to build the project I get the following error:

Cannot find JsonWriter or JsonFormat for type class List[MyClass]

spray-json has already a format for generic list and I'm providing a format for my class, what would be the problem?

Thanks in advance...!!!

like image 605
leonfs Avatar asked Oct 28 '14 17:10

leonfs


1 Answers

When I extended MyClassJsonFormat from JsonFormat instead of JsonWriter, it stared working fine. Looks like the CollectionFormats trait will work only if you extend from JsonFormat

The following code compiles fine for me

  object MyClassJsonProtocol extends DefaultJsonProtocol {

    implicit object MyClassJsonFormat extends JsonFormat[MyClass] {
    override def write(obj: MyClass): JsValue =
      JsObject(
        "name" -> JsString(obj.name)
      )

      override def read(json: JsValue): MyClass = new MyClass(json.convertTo[String])
    }
  }
like image 125
Vishal John Avatar answered Nov 01 '22 00:11

Vishal John