使用 Circe 将字段添加到 json

Maa*_*mon 6 scala json-ld circe

我正在阅读 circe 文档,但无法弄清楚如何处理以下问题。

我只想在主 JSON 对象中添加一个带有对象的字段。

{
  Fieldalreadythere: {}
  "Newfield" : {}
}
Run Code Online (Sandbox Code Playgroud)

我只想Newfield在对象中添加。为了提供一些上下文,我正在处理 Json-ld。我只想添加一个上下文对象。@context:{} 请参见下面的示例:

{
  "@context": {
    "@version": 1.1,
    "xsd": "http://www.w3.org/2001/XMLSchema#",
    "foaf": "http://xmlns.com/foaf/0.1/",
    "foaf:homepage": { "@type": "@id" },
    "picture": { "@id": "foaf:depiction", "@type": "@id" }
  },
  "@id": "http://me.markus-lanthaler.com/",
  "@type": "foaf:Person",
  "foaf:name": "Markus Lanthaler",
  "foaf:homepage": "http://www.markus-lanthaler.com/",
  "picture": "http://twitter.com/account/profile_image/markuslanthaler"
}
Run Code Online (Sandbox Code Playgroud)

我想添加上下文对象,仅此而已。

我怎么能用circe做到这一点。官方文档中的例子主要是讲修改值,但没有实际添加字段等。

小智 11

看看JsonObject。有:+方法可以满足您的需求。

这是一个简单的例子:

import io.circe.generic.auto._
import io.circe.parser
import io.circe.syntax._

object CirceAddFieldExample extends App {
    val jsonStr = """{
       Fieldalreadythere: {}
    }"""
    val json = parser.parse(jsonStr)
    val jsonObj = json match {
       case Right(value) => value.asObject
       case Left(error) => throw error
    }
    val jsonWithContextField = jsonObj.map(_.+:("@context", contextObj.asJson))
}
Run Code Online (Sandbox Code Playgroud)


Cal*_*lum 6

您可以使用该deepMerge方法将两个Json相加。

假设编码器可用于您的上下文类:

val contextJson: Json = Map("@context" -> context).asJson
val result: Json = existingJson.deepMerge(contextJson)
Run Code Online (Sandbox Code Playgroud)