Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unmarshalling nested JSON object with single field fails #3

Closed
dbronecki opened this issue May 19, 2017 · 1 comment · Fixed by #10
Closed

Unmarshalling nested JSON object with single field fails #3

dbronecki opened this issue May 19, 2017 · 1 comment · Fixed by #10
Labels

Comments

@dbronecki
Copy link
Contributor

The following test case:

import org.scalatest.{Matchers, WordSpec}
import pl.iterators.kebs.json.KebsSpray
import spray.json.DefaultJsonProtocol

case class Book(name: String, chapters: List[Chapter])
case class Chapter(name: String)

class KebsTest extends WordSpec with Matchers {

  import ThingProtocol._
  import spray.json._

  "Kebs" should {
    "work with nested single field objects" in {
      val json =
        """
          | {
          |   "name": "Functional Programming in Scala",
          |   "chapters": [{"name":"first"}, {"name":"second"}]
          | }
        """.stripMargin

      json.parseJson.convertTo[Book] shouldBe Book(
        name     = "Functional Programming in Scala",
        chapters = List(Chapter("first"), Chapter("second"))
      )
    }
  }
}

object ThingProtocol extends DefaultJsonProtocol with KebsSpray

Gives error:

spray.json.DeserializationException: Expected String as JsString, but got {"name":"first"}
@marcin-rzeznicki
Copy link
Contributor

So, you can prefer noflat format in current state of things, by marking it explicitly as RootJsonFormat like this:

implicit val chapterRootFormat: RootJsonFormat[Chapter] = jsonFormatN[Chapter]

or, you should have been able to do this, but there'd been bug preventing this usage (fixed in c3bbdeb). I personally prefer this in case you do not have many no-flats . In case where, say, most of what you serialize should be no-flat I think that we should add a trait which simply changes the preference. The problem with annotation like @noflat you added in #10 is that it couples JSON rendering with model definition, akin to slick's @MappedTo . But, I think it is worthy addition nonetheless, especially for people that do not object to this coupling, so we'll merge this PR as well.

marcin-rzeznicki added a commit that referenced this issue May 23, 2017
Fix issue #3 by adding special annotation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants