将任何 Scala 对象转换为 JSON [英] Convert any Scala object to JSON

查看:78
本文介绍了将任何 Scala 对象转换为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

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

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

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") 
  })
}

到那时,您可以通过在要序列化 ​​Any 的位置导入隐式值来使用它:

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

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

这篇关于将任何 Scala 对象转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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