简体   繁体   English

跳过 Json 序列化中的键

[英]Skip key in Json serialization

I have the following case class specification我有以下案例类规范

case class A(messages: Vector[SomeClass])

I would like to avoid to have a serialization result like the following:我想避免出现如下序列化结果:

{ 
    "messages":[{...},{...}]
}

I would like to skip the JsonObject specification and serialize the contents directly.我想跳过 JsonObject 规范并直接序列化内容。 So the result would look like:所以结果看起来像:

[
    {
        "key":"a"
    },
    {
        "key":"b"
    }
]

I have tried specifying an implicit converter like the following我曾尝试指定一个隐式转换器,如下所示

object A {
    implicit val writes:[Writes] = (o: A) => JsArray(o.messages.map(Json.toJson(_)))
    // also tried this Json.arr(o.messages.map(Json.toJson(_))) which has the same result 
}

but this produces an array inside an array但这会在数组内生成一个数组

[
    [
        {
            "key":"a"
        },
        {
            "key":"b"
        }
    ]
]

SomeClass is a sealed trait and its extensions are properly serialized and deserialized. SomeClass是一个密封的 trait,它的扩展被正确地序列化和反序列化。 My problem is with the array nesting of case class A .我的问题是案例类A的数组嵌套。 Any ideas?有任何想法吗?

You can use Writes.contramap and Reads.map , with Writes.seq and Reads.seq .您可以将Writes.contramapReads.mapWrites.seqReads.seq

import play.api.libs.json._

case class SomeClass(foo: String)

implicit val format1: OFormat[SomeClass] = Json.format

case class A(messages: Vector[SomeClass])

// Writes
implicit def writes(implicit w: OWrites[SomeClass]): Writes[A] =
  Writes.seq[SomeClass].contramap[A](_.messages)

Json.toJson(A(Vector(SomeClass("bar"))))
// play.api.libs.json.JsValue = [{"foo":"bar"}]

// Reads
implicit def reads(implicit r: Reads[SomeClass]): Reads[A] =
  Reads.seq[SomeClass].map { seq => A(seq.toVector) }

Json.parse("""[{"foo":"bar"}]""").validate[A]
// play.api.libs.json.JsResult[A] = JsSuccess(A(Vector(SomeClass(bar))),)

Just extract the Vector with your case class first:只需首先使用您的case class提取Vector

import play.api.libs.json._

val a: A = ???
Json.toJson(a.messages)

What you would need is the format for SomeClass :您需要的是SomeClass的格式:

object SomeClass {
  implicit val jsonFormat: Format[SomeClass] = Json.format[SomeClass]
}

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

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