Spray-json for regular classes (if absent) in the list

I am in a situation where I need to serialize to JSON class without case.

The presence of a class like:

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

I created 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 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 I try to create a project, I get the following error:

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

spray-json already has a format for the general list, and I am providing a format for my class, what is the problem?

Thanks in advance...!!!

+6
source share
2 answers

When I extended MyClassJsonFormat from JsonFormat instead of JsonWriter , it looked like it works. It looks like the CollectionFormats property will only work if you extend from JsonFormat

The following code compiles 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]) } } 
+3
source

The reason is apparently mentioned here :

The problem you may encounter with JsonReader / JsonWriter is that when you try to find JsonReader / JsonWriter for an option or collection, it is looking for JsonFormat for a hidden type that will fail. Not sure if there is something that I don’t see that will fix this problem.

We are faced with this. At the moment, I see no other option than @ user007 to use full JsonFormat . This, in itself, brings more difficulties, at least for me - I planned to use the default for my class.

Oh well ...

0
source

Source: https://habr.com/ru/post/977365/


All Articles