scala-将超过22个元素的json解析为case类 [英] scala - parse json of more than 22 elements into case class

查看:346
本文介绍了scala-将超过22个元素的json解析为case类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题或类似问题已在以前发布,但是所有解决方案都无法与最新库一起使用.到目前为止,经过广泛的搜索,我发现没有证据表明最受欢迎的库spray-jsonplay-json(或其插件)的最新版本可以处理这种情况.有什么可以将超过22个元素的json解析为scala case类吗?从scala 2.11开始,案例类不再局限于22个元素.请只提供完整的解决方案.下面是明显的json示例.

This question or similar ones were posted before, however none of the solutions work any more with latest libraries. After extensive searching as of now I found no evidence that latest versions of most popular libraries spray-json or play-json (or their plugins) can handle this case. Is there something that can parse a json of more than 22 elements into scala case class? Since scala 2.11 case classes are no longer limited to 22 elements. Please, only fully working solutions. Obvious json example below.

{
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    "e": 5,
    "f": 6,
    "g": 7,
    "h": 8,
    "i": 9,
    "j": 10,
    "k": 11,
    "l": 12,
    "m": 13,
    "n": 14,
    "o": 15,
    "p": 16,
    "q": 17,
    "r": 18,
    "s": 19,
    "t": 20,
    "u": 21,
    "v": 22,
    "w": 23
}

更新:在这种情况下,您无法控制json结构,例如,它是从第3方api检索的. Twitter的tweet json示例: http://pastebin.com/h8fHAsd8

UPDATE: This is a case when you have no control over json structure, for instance it's retrieved from a 3rd party api. An example of twitter's tweet json: http://pastebin.com/h8fHAsd8

推荐答案

圈子可以,并且无形.请注意,与json4s的case类解码不同,这里没有发生运行时反射:

circe does, with automatic codec derivation supported by Shapeless. Note that unlike json4s's case class decoding, there's no runtime reflection happening here:

case class Foo(
  a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, h: Int, i: Int,
  j: Int, k: Int, l: Int, m: Int, n: Int, o: Int, p: Int, q: Int, r: Int,
  s: Int, t: Int, u: Int, v: Int, w: Int
)

import io.circe.generic.auto._, io.circe.jawn.decode

val json = """{
  "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9,
  "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17,
  "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23
}"""

val result: cats.data.Xor[io.circe.Error, Foo] = decode[Foo](json)

这是最小的build.sbt文件:

scalaVersion := "2.11.7"

addCompilerPlugin(
  "org.scalamacros" % "paradise" % "2.1.0-M5" cross CrossVersion.full
)

libraryDependencies ++= Seq(
  "io.circe" %% "circe-core" % "0.1.1",
  "io.circe" %% "circe-generic" % "0.1.1",
  "io.circe" %% "circe-jawn" % "0.1.1"
)

即将发布的0.2.0版本(当前可作为快照)对通用派生进行了许多改进,但对于像这样的简单示例,0.1.1行为是相同的.

The upcoming 0.2.0 release (currently available as a snapshot) includes a lot of improvements to generic derivation, but for a simple example like this the 0.1.1 behavior is the same.

这篇关于scala-将超过22个元素的json解析为case类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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