score:20
Definitely use spray json. Usually you separate the data models into their own file:
import spray.json._
case class Foo(a: String, b: Int)
case class Bar(c: Long, d: String)
object FooBarJsonProtocol extends DefaultJsonProtocol{
implicit val fooFormat = jsonFormat2(Foo)
implicit val barFormat = jsonFormat2(Bar)
}
Then in the route
import FooBarJsonProtocol._
...
get {
path("foo") {
complete {
listOfFoo() //with the implicit in scope this will serialize as json
}
}
} ~ post {
path("bar") {
entity(as[Bar]) { bar => //extract json Bar from post body
complete(bar) //serialize bar to json (or whatever processing you want to do)
}
}
}
}
score:2
Got it thanks, here is my answer
import spray.routing._
import spray.json._
import spray.httpx._
import spray.http._
case class UserLogin(username: String, password: String)
object UserLoginJsonSupport extends DefaultJsonProtocol with SprayJsonSupport {
implicit val PortofolioFormats = jsonFormat2(UserLogin)
}
import UserLoginJsonSupport._
trait UserAccountsServiceAPI extends HttpService{
val UserAccountsServiceRouting = {
path("api" / "userservice" ) {
post {
entity(as[UserLogin]) { userLogin =>
println("->"+userLogin.username)
println("->"+userLogin.password)
complete(userLogin.username)
}
}
}
}
}
My http request with curl app
curl -i 'http://localhost:8080/api/userservice' -X POST -H "Content-Type: application/json" -d '{"username": "admin", "password": "pwd"}'
score:7
I can't imagine why this question was down-voted -- it seems specific and well-expressed.
It is a bit hard to find, but the Spray docs cover case class extraction under Spray Routing / Advanced Topics. It would be pointless to repeat their explanation here, but basically you want to use as[Foo]
to deserialize HTTP content into objects. The entity
directive can be used to do this for the body of a request, as shown in this longer example of the spray-routing DSL. mapTo
(used in the same example) is probably what you want to serialize an object for the response.
For JSON, it would probably be easiest to use their separate Spray-JSON library, since it plugs right into their typeclass mechanism, but I think you could with some effort marry up anything you want. Spray-JSON can handle a case class with one line of glue.
By the way, the line val bar: Bar = ???
in your sample code is going to be executed at the time the route is defined, not when a request comes in, as you presumably want. Please read the Understanding the DSL Structure section of the spray-routing docs.
Source: stackoverflow.com
Related Query
- Write a simple json REST server using spray in scala
- Write a thrift server in scala using scrooge and client in python or ruby
- Error while doing a very basic test of http server using scala akka spray can
- Write an Arbitrary Value Not Found in a Case Class Using Play's (2.2) Scala JSON Combinators
- Simple JSON to XML and then XML to JSON using Scala
- Write a map with key as int to json in scala using json4s
- Serializing/Deserializing model using spray json scala test
- convert json to array of scala objects using spray json
- scala Spray Rest API return Json content type with RequestContext
- Apply custom schema to post response JSON from rest api using scala spark
- Parsing simple json string using scala built in functions
- (Un)marshall JSON with named root for Ember Data using Scala case class on Spray
- How to parse JSON in Scala using standard Scala classes?
- How to load JSON file using Play with Scala
- Scala compile server error when using nailgun
- Serializing a scala object into a JSon String using lift-json
- How to write copy() method for Simple Class in Scala
- How is scala generating byte code? Using some libraries like ASM, or write binary directly?
- JSON serialization of Scala enums using Jackson
- Using Finagle for simple Scala SOAP client
- Encoding Scala None to JSON value using circe
- Forwarding HTTP/REST Request to another REST server in Spray
- Print json string in one line using circe in scala
- How to add a json object in to a json array using scala play?
- How to write to HDFS using Scala
- Scala Dynamic Parse Json using case class No Manifest available for T
- How to read json data using scala from kafka topic in apache spark
- How can I deserialize from JSON with Scala using *non-case* classes?
- Re-using A Schema from JSON within a Spark DataFrame using Scala
- Parse JSON array using Scala Argonaut
More Query from same tag
- performance enhancement using flatMap vs for-comprehension
- Migrating from Matlab to Saddle: How to mutate a matrix selection?
- Multi module Scala Play 2.3 conf location
- Adding mapping to collections.mutable.Map fails when map is empty
- Java/Kotlin- Akka Stream Source.reduce does not work if null in Source
- Scala generic List implementation
- Deploy Scala binaries without dependencies
- Slick transform subset of Table Columns into a Case Class
- collect_set equivalent spark 1.5 UDAF method verification
- SBT multi project in Intellij
- Scala : Match particular word and count frequency
- How to parse json using json4s so that let primitive values become custom case class?
- Can You Import Dynamically in Scala?
- Applicative style using cats library
- Gatling Scala "not found: type ExtraInfo" error found when running performance test
- A more efficent way to check if an array in scala resembles to a range
- Spark Scala Unit test getting failed
- Both TreeMap and TreeSet create a new empty incarnation TreeMap.empty, TreeSet.empty. Is this fixable?
- Scala method call with generic arguments appears not polymorphic - what is wrong
- Using Scala to cut up a large CSV file
- Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/mutable/SynchronizedBuffer$class
- scala vs java for Spark?
- How do I write recursive anonymous functions?
- Scala 3 Manifest replacement
- Akka, Generic ActorRef?
- Convert Seq[Try[Option(String, Any)]] into Try[Option[Map[String, Any]]]
- How to parallel process files recieved in a zip file format?
- Akka pattern for handling asynchronous actions in receive
- Async callback from Akka Actor
- How to run scala specs 2 in eclipse