Jackson ObjectNode: how to not include NULL on serialization

时间:2016-08-31 17:32:17

标签: json scala null jackson

I'm having trouble excluding Null/Empty properties when I serialize my ObjectNode back to a string. I googled around and all the references about JsonInclude.Include.NON_NULL are regarding serializing and deserializing from a Bean, not an ObjectNode - It seams that the serialization behaves differently from an "arbitrary" ObjectNode instead of a pre-defined Bean.

My goal is to have the output = {"name":"myName"}, Not {"name":"myName","nu":null,"empt":""}

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.ObjectMapper

val jsonInputStr = """{"name": "myName"}"""
val newObjMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY)

val json = newObjMapper.readTree(jsonInputStr).asInstanceOf[ObjectNode]
json.put("nu", null.asInstanceOf[String])
json.put("empt", "")
val str = newObjMapper.writeValueAsBytes(json)
println(s"OUTPUT = ${new String(str)}")

prints: OUTPUT = {"name":"myName","nu":null,"empt":""}

1 个答案:

答案 0 :(得分:0)

If you deserialize the JSON into a Map instead of a JsonNode structure, when you re-serialize the Map, it will obey the serialization inclusion parameters.

Edit to address comment:

If you want to use the node structure and don't mind a slight performance hit of doing multiple serialization steps, then you could always do something like:

val rootNode = objectMapper.readTree(...)
...
val map = objectMapper.treeToValue(rootNode, Map::class)
val json = objectMapper.writeValueAsString(map)