简体   繁体   English

将Scala案例类转换为json

[英]Convert scala case class to json

I need to convert scala case class to json.我需要将 Scala 案例类转换为 json。 I am using spray json.我正在使用喷雾 json。 The problem is my case class having more then 22 fields, and spray json supports to 22 fields only.问题是我的案例类有超过 22 个字段,而 Spray json 仅支持 22 个字段。

I cant write like我写不出来

implicit val someformat = jsonformat25(Somecaseclass)

case class Color(name: String, red: Int, green: Int, blue: Int)

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val colorFormat = jsonFormat4(Color)
}

import MyJsonProtocol._
import spray.json._

val json = Color("CadetBlue", 95, 158, 160).toJson
val color = json.convertTo[Color]

I saw there is and tried with it, but it's not working.我看到有并尝试使用它,但它不起作用。 Please suggest some solution.请提出一些解决方案。

implicit object format extends RootJsonFormat[SomeObject] {
    def write(a: SomeObject) = a match {
      case p: SomeObject=> p.toJson
    }
    def read(value: JsValue) = {
      value.convertTo[SomeObject]
    }
  }

Please dont suggest to split class params and make nested case class.. my requirements are I have more than 22 fields in one case class.请不要建议拆分类参数并制作嵌套的案例类..我的要求是我在一个案例类中有超过 22 个字段。

You could use - https://github.com/sitetester/json-handler你可以使用 - https://github.com/sitetester/json-handler

  • It's easy to use and supports converting nested case class(s) into JSON with proper indentation.它易于使用并支持将嵌套的 case 类转换为具有适当缩进的 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM