Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unmarshall `text/plain` as JSON in Akka HTTP

I'm working with a legacy HTTP API (that I can't change) that responds with JSON in the body, but gives a Content-Type: text/plain; charset=utf-8 header.

I am attempting to unmarshall that HTTP body as JSON, but I get the following exception: akka.http.scaladsl.unmarshalling.Unmarshaller$UnsupportedContentTypeException: Unsupported Content-Type, supported: application/json

My code looks like this:

import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.unmarshalling._

case class ResponseBody(status: String, error_msg: String)

object ResponseBodyJsonProtocol extends DefaultJsonProtocol {
  implicit val responseBodyFormat = jsonFormat2(ResponseBody)
}

def parse(entity: HttpEntity): Future[ResponseBody] = {
  implicit val materializer: Materializer = ActorMaterializer()
  import ResponseBodyJsonProtocol._
  Unmarshal[HttpEntity](entity).to[ResponseBody]
}

A sample HTTP response looks like this:

HTTP/1.1 200 OK
Cache-Control: private
Content-Encoding: gzip
Content-Length: 161
Content-Type: text/plain; charset=utf-8
Date: Wed, 16 Dec 2015 18:15:14 GMT
Server: Microsoft-IIS/7.5
Vary: Accept-Encoding
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET

{"status":"1","error_msg":"Missing parameter"}

What can I do to ignore the Content-Type in the HTTP response and parse as JSON?

like image 975
David van Geest Avatar asked Dec 16 '15 18:12

David van Geest


2 Answers

One workaround I found was to just manually set the Content-Type on the HttpEntity before unmarshalling it:

def parse(entity: HttpEntity): Future[ResponseBody] = {
  implicit val materializer: Materializer = ActorMaterializer()
  import ResponseBodyJsonProtocol._
  Unmarshal[HttpEntity](entity.withContentType(ContentTypes.`application/json`)).to[ResponseBody]
}

Seems to work OK, but I'm open to other ideas...

like image 115
David van Geest Avatar answered Oct 31 '22 13:10

David van Geest


I'd use map... directive. It looks short and elegant.

val routes = (decodeRequest & encodeResponse) {
  mapResponseEntity(_.withContentType(ContentTypes.`application/json`)) {
    nakedRoutes ~ authenticatedRoutes
  }
}
like image 2
expert Avatar answered Oct 31 '22 14:10

expert