Adding field to a json using Circe

流过昼夜 提交于 2019-12-12 14:08:11

问题


I am going trough the circe documentation and can't figure out how to handle the following.

I would simply like to add a field with an object in said the main jason object.

{
  Fieldalreadythere: {}
  "Newfield" : {}
}

I just want to add the newfield in the object. To give a bit of context i am dealing with Json-ld. I just want to add a context object. @context: {} See example bellow:

{
  "@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"
}

I would like to add the context object, that's all.

How can i do that with circe. The example in the official documentation mostly talk about modifying value, but nothing to actually add field and so on.


回答1:


Take a look at JsonObject. There is :+ method that does what you want.

Here's a simple example:

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))
}



回答2:


You can use the deepMerge method to add two Json together.

Assuming an encoder is available for your context class:

val contextJson: Json = Map("@context", context).asJson
val result: Json = existingJson.deepMerge(contextJson)


来源:https://stackoverflow.com/questions/53681757/adding-field-to-a-json-using-circe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!