简体   繁体   English

Scala / Play:JSON序列化问题

[英]Scala/Play: JSON serialization issue

I have a simple custom data structure which I use to map the results from the database: 我有一个简单的自定义数据结构,我用它来映射数据库的结果:

case class Filter(id: Int, table: String, name: String, Type: String, structure: String)

The resulting object type is List[Filter] and if converted to JSON, it should look something like this: 生成的对象类型是List[Filter] ,如果转换为JSON,它应该如下所示:

[
    {
        "id":           1,
        "table":        "table1",
        "name":         "name1",
        "Type":         "type1",
        "structure":    "structure1"
    },
    {
        "id":           2,
        "table":        "table2",
        "name":         "name2",
        "Type":         "type2",
        "structure":    "structure2"
    }
]

Now when I try to serialize my object into JSON 现在,当我尝试将对象序列化为JSON时

val result: String = Json.toJson(filters)

I am getting something like 我得到了类似的东西

No Json deserializer found for type List[Filter]. Try to implement an implicit Writes or Format for this type.

How do I solve this seemingly simple problem without writing some ridiculous amount of boilerplate? 如何在不编写一些荒谬的样板的情况下解决这个看似简单的问题?

My stack is Play 2.2.1, Scala 2.10.3, Java 8 64bit 我的堆栈是Play 2.2.1,Scala 2.10.3,Java 8 64bit

Short answer : 简短回答

Just add: 只需添加:

implicit val filterWrites = Json.writes[Filter]

Longer answer : 更长的回答

If you look at the definition of Json.toJson, you will see that its complete signature is: 如果你看一下Json.toJson的定义,你会发现它的完整签名是:

def toJson[T](o: T)(implicit tjs: Writes[T]): JsValue = tjs.writes(o)

Writes[T] knows how to take a T and transform it to a JsValue . Writes[T]知道如何获取T并将其转换为JsValue You will need to have an implicit Writes[Filter] around that knows how to serialize your Filter instance. 你需要有一个隐含的Writes[Filter] ,知道如何序列化你的Filter实例。 The good news is that Play's JSON library comes with a macro that can instantiate those Writes[_] for you, so you don't have to write boring code that transforms your case class's fields into JSON values. 好消息是,Play的JSON库附带了一个宏,可以为您实例化那些Writes[_] ,因此您不必编写将案例类的字段转换为JSON值的无聊代码。 To invoke this macro and have its value picked up by implicit search add the line above to your scope. 要调用此宏并通过隐式搜索获取其值,请将上面的行添加到您的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM