(Un)使用Spray上的Scala案例类将Ember Data的名称为root的JSON编组为JSON [英] (Un)marshall JSON with named root for Ember Data using Scala case class on Spray

查看:107
本文介绍了(Un)使用Spray上的Scala案例类将Ember Data的名称为root的JSON编组为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个RESTful接口,我想编组和解组JSON,以准备Ember Data. 问题在于Ember Data想要实体名称,而我尝试使用的两个库Spray-json和json4s似乎并不容易做到这一点.

I am writing a RESTful interface and I would like to marshall and unmarshall JSON ready for Ember Data. The wrinkle is that Ember Data wants the entity name and the two libraries I've tried, spray-json and json4s, don't appear to do this easily.

所需的 Ember数据格式

{
  "coursePhoto": {
    "photoId": 1
  }
}

当前默认格式:

{"photoId":15}

这应该来自案例类:

case class CoursePhoto(photoId: Long)

我确实使用以下自定义代码运行它:

I did get it running with the following custom code:

object PtolemyJsonProtocol extends DefaultJsonProtocol {
  implicit object CoursePhotoFormat extends RootJsonFormat[CoursePhoto] {
  def write(cp: CoursePhoto) =
    JsObject("CoursePhoto" -> JsObject("photoId" -> JsNumber(cp.photoId)))  
  def read(value: JsValue) = value match {
    case coursePhotoJsObject: JsObject => {
      CoursePhoto(coursePhotoJsObject.getFields("CoursePhoto")(0).asJsObject
      .getFields("photos")(0).asInstanceOf[JsArray].elements(0)
      .asInstanceOf[JsNumber].value.toLong)
    }            
    case _ => deserializationError("CoursePhoto expected")
  }
}

对于所有asInstanceOf(0),该代码似乎都非常脆弱和丑陋.

That code seems horrifyingly fragile and ugly with all the asInstanceOf and (0).

鉴于我正在使用Spray与Scala编写代码,获取命名根JSON输出的好方法是什么?我很高兴使用与Spray很好地集成并且性能合理的JSON库来做到这一点.

Given that I'm writing in Spray with Scala what's the nice way to get named root JSON output? I am quite happy to do this with any JSON library that integrates nicely with Spray and is reasonably performant.

推荐答案

以下方法可以解决您的问题吗?

Is the following solving your problem?

scala> import spray.json._
import spray.json._

scala> import DefaultJsonProtocol._
import DefaultJsonProtocol._

scala> case class CoursePhoto(photoId: Long)
defined class CoursePhoto

scala> case class CoursePhotoEmber(coursePhoto: CoursePhoto)
defined class CoursePhotoEmber

scala> implicit val jsonFormatCoursePhoto = jsonFormat1(CoursePhoto)
jsonFormatCoursePhoto: spray.json.RootJsonFormat[CoursePhoto] = spray.json.ProductFormatsInstances$$anon$1@6f5d66b6

scala> implicit val jsonFormatCoursePhotoEmber = jsonFormat1(CoursePhotoEmber)
jsonFormatCoursePhotoEmber: spray.json.RootJsonFormat[CoursePhotoEmber] = spray.json.ProductFormatsInstances$$anon$1@401a0d22

scala> """{ "coursePhoto": { "photoId": 1 } }""".parseJson.convertTo[CoursePhotoEmber]
res0: CoursePhotoEmber = CoursePhotoEmber(CoursePhoto(1))

scala> res0.toJson
res1: spray.json.JsValue = {"coursePhoto":{"photoId":1}}

这篇关于(Un)使用Spray上的Scala案例类将Ember Data的名称为root的JSON编组为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆