0

Im working on a project that has scala backend and scalatra as a servlet. For now, the backend is running inside a Vagrant box, and sbt is used to build the program.

My problem is that I need to handle incoming Json-formatted data, but I cant extract it properly - though I'm able to send Json data. First I played around with Scalas own Json parser, but realized that it's deprecated, so I had to find external library. After that I came up with json4s.

In my app I have the following endpoint listening for incoming post requests

post("/my/endpoint") {
    // run the code in here
}

And that works just fine. I can put trivial println inside the brackets and it displays in the sbt shell after the endpoint has been called.

After that I defined a case class to be used to extract the data

case class Person(name : String) {
  override def toString() = s"My name is $name"
}

And lastly I did the following code inside my endpoint function

post("/my/endpoint") {
  val json = parse(request.body)
  val person = json.extract[Person]
  println(person)
}

So right now when calling the println it should print whatever the toString method of Person class returns, but it prints nothing.

Lets take a step back and modify the code so that we have the following

post("/my/endpoint") {
  val json = parse(request.body)
  println(json)
}

This piece of code prints the following into sbt shell

JObject(List((name,JString(joe))))

So we can see that the parse-function is actually doing something and data is being received.

But, if we add

person = json.extract[Person]

after println(json), the endpoint stops functioning. Why I think it's weird, is because it's not a compiling error, so everything before that line should work properly? Also it doesn't cause the program to crash on runtime, nor does it give any errors, warnings, etc. Every other endpoint and functions works still properly.

Also, I did try the example in json4s.org under the section 'Extracting values'. I copied the code from word to word, but that did not work either.

Also FYI, my versions are SBT, 1.1.6, Scala 2.12.6, Scalatra 2.6.3, json4s 3.5.2 and Vagrant is using Xenial 16.04 as its basebox.

pls help mi

  • 1
    I tested the code as you described and it worked well. You can see my project at: https://github.com/takezoe/scalatra-json-example Can you find any differences in your code? – Naoki Takezoe Jun 22 '18 at 04:54
  • I got back to work now and was able to test your code, and it worked. The problem was that I nested my case classes inside the trait that I had all my routes in. After moving the case classes outside of that trait it worked fine. Thank you – Lasse Liimatta Jun 25 '18 at 06:06

0 Answers0