将任何 Scala 对象转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22985098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:10:57  来源:igfitidea点击:

Convert any Scala object to JSON

jsonscalaplayframeworkplayframework-2.2

提问by Vilis

I am using latest version of Play Framework and it's JSON lib like this Json.toJson(obj). But toJson is not capable of converting any Scala object to JSON, because the structure of data is unknown. Someone suggested using case convert, but here my Scala knowledge falls short. The data comes from database, but the structure of table is not known.

我正在使用最新版本的 Play Framework,它是这样的 JSON 库Json.toJson(obj)。但是 toJson 不能将任何 Scala 对象转换为 JSON,因为数据的结构是未知的。有人建议使用 case convert,但在这里我的 Scala 知识不足。数据来自数据库,但不知道表的结构。

Where should I look further to create convert such unknown data structure to JSON?

我应该在哪里进一步创建将这种未知数据结构转换为 JSON?

采纳答案by tehlexx

Given that there is only a limited number of types you want to serialize to JSON, this should work:

鉴于您想要序列化为 JSON 的类型数量有限,这应该有效:

object MyWriter {
  implicit val anyValWriter = Writes[Any] (a => a match {
    case v:String => Json.toJson(v)
    case v:Int => Json.toJson(v)
    case v:Any => Json.toJson(v.toString)
    // or, if you don't care about the value
    case _ => throw new RuntimeException("unserializeable type") 
  })
}

You can use it by then by importing the implicit value at the point where you want to serialize your Any:

然后,您可以通过在要序列化的点导入隐式值来使用它Any

import MyWriter.anyValWriter
val a: Any = "Foo"
Json.toJson(a)

回答by Cassio

Using json4s, you can import the package:

使用 json4s,您可以导入包:

import org.json4s.DefaultFormats
import org.json4s.native.Serialization.write

Then create an implicit variable inside your trait:

然后在您的特征中创建一个隐式变量:

implicit val formats: DefaultFormats = DefaultFormats

And finally, in your method, use it:

最后,在您的方法中,使用它:

write(myObject)