Read JSON tree structure in Scala Play Framework

I am trying to process an AJAX POST request in Play Framework 2.1.3. Mail data are JSON objects and have a tree structure, for example:

{ id: "a", name: "myname", kids : [{ id: "a1", name : "kid1", kids: []}, {id: "a2", name: "kid2", kids: [{id: "aa1", name :"grandkid", kids: []}]}] 

I would like a nest of "children" arbitrarily deep. The class I would like to keep in mind is similar to this (I understand that recursiveness can be problematic):

 case class Person { id: String, name: String, kids: Array[Person] } 

The format I would like to keep in mind:

 implicit val personFormat:Format[Person] = Json.format[Person] 

The game throws errors in my format, which I wrote:

type mismatch; found: controller.Resources.Person required: Array [controller.Resources.Person]

I know that Play has a Tree structure. I could not find examples / documentation on how to link this to JSON reading.

Any help is much appreciated, thanks

+6
source share
2 answers

You will need a recursive val, something like:

 implicit val jsonReads: Reads[Person] = ((__ \ "id").read[String] and (__ \ "name").read[String] and (__ \ "kids").read[Seq[Person]])(apply _) 

(I changed the type of the collection from Array to Seq because it is more general and allows you to change your implementation without affecting the downstream code.)

The syntax used here is .

+9
source

The only way I see this work is to use JsArray or Array [String] instead of Array [Person] in your case Person class. JSON Macro Inception can only generate read + write code for primitives and lists, maps and arrays for objects for which an implicit read + write JSON code already exists. Essentially, you cannot have a case class that references itself.

 package models import play.api.libs.json._ case class Person( id : String, name : String, kids : JsArray ) object Person extends ((String,String,JsArray) => Person) { implicit val jsonFormat = Json.format[Person] } 
+2
source

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


All Articles