在Scala中将一种格式的JSON转换为另一种格式

在Scala中将一种格式的JSON转换为另一种格式

本文介绍了在Scala中将一种格式的JSON转换为另一种格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找可以帮助我在Scala中将JSON(具有嵌套结构)从一种格式转换为另一种格式的建议或库。

I'm looking for suggestions or libraries that can help me convert JSON (with nested structure) from one format to another in Scala.

我看到有一些基于JavaScript和Java的解决方案。 Scala中有什么吗?

I saw there are a few JavaScript and Java based solutions. Anything in Scala ?

推荐答案

我真的很喜欢Play JSON库。它的API非常干净,即使某些部分的学习曲线稍微陡峭也非常快。即使您未使用其余的Play,也可以使用Play JSON库。

I really like the Play JSON library. It's API is very clean and it's very fast even if some parts have a slightly steeper learning curve. You can also use the Play JSON library even if you aren't using the rest of Play.

将JSON转换为Scala对象(反之亦然),Play使用隐式对象。 读取类型指定如何将JSON转换为scala类型,而 Writes 类型指定如何将JSON转换为scala类型。将标量对象转换为JSON。

To convert JSON to scala objects (and vice versa), Play uses implicits. There is a Reads type which specifies how to convert JSON to a scala type, and a Writes type which specifies how to convert a scala object to JSON.

例如:

case class Foo(a: Int, b: String)

您可以选择以下几种路线将 Foo 转换为JSON。如果您的对象很简单(例如 Foo ),则Play JSON可以为您创建转换函数:

There are a few different routes you can take to convert Foo to JSON. If your object is simple (like Foo), Play JSON can create a conversion function for you:

implicit val fooReads = Json.reads[Foo]

或者您可以创建如果您想要更多控制权或您的类型更复杂,请使用自定义转换函数。以下示例为 Foo a 使用名称 id c>:

or you can create a custom conversion function if you want more control or if your type is more complex. The below examples uses the name id for the property a in Foo:

implicit val fooReads = (
  (__ \ "id").read[Int] ~
  (__ \ "name").read[String]
)(Foo)

写入类型具有相似的功能:

The Writes type has similar capabilities:

implicit val fooWrites = Json.writes[Foo]

implicit val fooWrites = (
   (JsPath \ "id").write[Int] and
   (JsPath \ "name").write[String]
)(unlift(Foo.unapply))

您可以阅读有关读取 / 写入(以及您需要的所有导入内容):

You can read more about Reads/Writes (and all the imports you will need) here: https://playframework.com/documentation/2.3.x/ScalaJsonCombinators

您还可以转换JSON,而无需在scala类型之间映射JSON。这是快速的并且通常需要更少的样板。一个简单的例子:

You can also transform your JSON without mapping JSON to/from scala types. This is fast and often requires less boilerplate. A simple example:

import play.api.libs.json._

// Only take a single branch from the input json
// This transformer takes the entire JSON subtree pointed to by
// key bar (no matter what it is)
val pickFoo = (__ \ 'foo).json.pickBranch

// Parse JSON from a string and apply the transformer
val input = """{"foo": {"id": 10, "name": "x"}, "foobar": 100}"""
val baz: JsValue = Json.parse(input)
val foo: JsValue = baz.transform(pickFoo)

您可以在此处阅读有关直接转换JSON的更多信息:

You can read more about transforming JSON directly here: https://playframework.com/documentation/2.3.x/ScalaJsonTransformers

这篇关于在Scala中将一种格式的JSON转换为另一种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:02