使用Jackson和Scala替换父Json节点中的json节点

时间:2018-08-23 06:51:42

标签: jsonpath jackson-databind

我有一个使用JsonPath加载的json模式,并且正在修改特定节点的值。现在,我需要将此节点放回根节点。我如何在杰克逊实现这一目标?

val objectMapper = new ObjectMapper()
    val rootNode : JsonNode  = objectMapper.readTree(uiSchema)
// I read the json schema above
    val jacksonJsonProvider = new JacksonJsonProvider()
    val jsonConfiguration = Configuration.defaultConfiguration.jsonProvider(jacksonJsonProvider)
    var modifiedUiSchemaString = uiSchema

    // Only if the value from domain data is a non empty array it will replace the value
    Try { //JsonArray is the array of SimulationSet Nodes.
      val simSetArray:ArrayNode = JsonPath.using(jsonConfiguration).parse(uiSchema).read(keyPath)
      if (simSetArray.size() > 0) {
        val simSetNode = simSetArray.get(0)
        val simSetDomainArray : ListBuffer[JsonNode] = new ListBuffer[JsonNode]()
        //Loop through List buffer and add to array and then add this array to ArrayNode
          simulationSetList.foreach(simulationSet => {
            val element = objectMapper.createObjectNode()
            element.put( "label", simulationSet)
            element.put ("value", simulationSet)
            simSetDomainArray.+=(element)

        })
      //First put the element back in simset and add this simSetNode to rootNode
        if (simSetDomainArray.nonEmpty && !(simSetNode.findValues("values") == simSetDomainArray.toList)) {
          simSetNode.("values", simSetDomainArray)
          modifiedUiSchemaString = objectMapper.writeValueAsString(rootNode)
        }
      }
    } match {
      case  _ => modifiedUiSchemaString
      case  Failure(f) => LOGGER.error(f.getStackTrace.toString)
        modifiedUiSchemaString
    }

在上面的代码中,我需要修改simSetNode中的values元素,然后需要将此simSetNode添加到rootNode,我该怎么做?

0 个答案:

没有答案