将任何Scala对象转换为JSON

编程入门 行业动态 更新时间:2024-10-28 19:34:26
本文介绍了将任何Scala对象转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用最新版本的Play Framework,并且它是JSON库,例如Json.toJson(obj).但是toJson不能将任何Scala对象转换为JSON,因为数据的结构是未知的.有人建议使用大小写转换,但是在这里我的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

本文发布于:2023-06-10 05:41:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/608210.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   对象   Scala   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!