【问题标题】:Convert List to Json将列表转换为 Json
【发布时间】:2021-08-27 06:57:27
【问题描述】:

如何创建一个如下所示的 Json (Circe):

{
 "items": [{
   "field1": "somevalue",
   "field2": "somevalue2"
  },
  {
   "field1": "abc",
   "field2": "123abc"
  }]
}

val result = Json.fromFields(List("items" -> ???))

【问题讨论】:

    标签: json circe


    【解决方案1】:

    您可以使用 Circe 的内置列表类型类来编码 JSON。此代码将起作用:

    import io.circe.{Encoder, Json}
    import io.circe.syntax._
    
    case class Field(field1: String, field2: String)
    
    object Field {
      implicit val encodeFoo: Encoder[Field] = new Encoder[Field] {
        final def apply(a: Field): Json = Json.obj(
          ("field1", Json.fromString(a.field1)),
          ("field2", Json.fromString(a.field2))
        )
      }
    }
    
    class Encoding(items: List[Field]) {
      def getJson: Json = {
        Json.obj(
          (
            "items", 
            items.asJson
          )
        )
      }
    }
    

    如果我们实例化一个“Encoding”类并调用 getJson,它将返回所需的 JSON。它之所以有效,是因为使用 circe 对列表进行编码所需要做的就是为列表中的任何内容提供编码器。因此,如果我们为 Field 提供编码器,当我们在其上调用 asJson 时,它将在列表中对其进行编码。

    如果我们运行这个:

    val items = new Encoding(List(Field("jf", "fj"), Field("jfl", "fjl")))
    
    println(items.getJson)
    

    我们得到:

    {
      "items" : [
        {
          "field1" : "jf",
          "field2" : "fj"
        },
        {
          "field1" : "jfl",
          "field2" : "fjl"
        }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多