本文介绍了如何使用Kotlin和杰克逊ObjectMapper从json中删除属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除以下JSON中所有出现的"attributeToRemove":
I want to remove all occurrence of "attributeToRemove" in the following JSON:
{
"Item994": [
{
"attributeToRemove": {
"someItem": null
},
"types": [
"type194",
"type294"
],
"p1": "SOS"
}
],
"Item99": [
{
"attributeToRemove": {
"someItem": null
},
"types": [
"type19",
"type29"
],
"p1": "SOS"
}
]
}
我尝试使用removeAll
,但出现此错误:Type mismatch: inferred type is (JsonNode!) -> JsonNode! but (JsonNode!) -> Boolean was expected
I tried using removeAll
but I keep this Error: Type mismatch: inferred type is (JsonNode!) -> JsonNode! but (JsonNode!) -> Boolean was expected
有人可以建议如何解决此问题吗?
Can anyone suggest how to fix this?
这是我的代码:
import com.fasterxml.jackson.databind.ObjectMapper
fun main ( args : Array < String > ) {
val someString = "{\n" +
" \"Item994\": [\n" +
" {\n" +
" \"attributeToRemove\": {\n" +
" \"someItem\": null\n" +
" },\n" +
" \"types\": [\n" +
" \"type194\",\n" +
" \"type294\"\n" +
" ],\n" +
" \"p1\": \"SOS\"\n" +
" }\n" +
" ],\n" +
" \"Item99\": [\n" +
" {\n" +
" \"attributeToRemove\": {\n" +
" \"someItem\": null\n" +
" },\n" +
" \"types\": [\n" +
" \"type19\",\n" +
" \"type29\"\n" +
" ],\n" +
" \"p1\": \"SOS\"\n" +
" }\n" +
" ]\n" +
"}"
val mapper = ObjectMapper()
val jsonStr = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(someString)
val jsonResult = mapper.readTree(someString)
jsonResult.removeAll { it.get("attributeToRemove") }
}
推荐答案
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
@JsonIgnoreProperties(ignoreUnknown = true)
class Item99 {
var p1: String? = null
var types: Array<String>? = null
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Item994 {
var p1: String? = null
var types: Array<String>? = null
}
class Wrapper {
@JsonProperty("Item99")
var item99: Array<Item99>? = null
@JsonProperty("Item994")
var item994: Array<Item994>? = null
}
object Main {
var jsonString = "{\n" +
" \"Item994\": [\n" +
" {\n" +
" \"attributeToRemove\": {\n" +
" \"someItem\": null\n" +
" },\n" +
" \"types\": [\n" +
" \"type194\",\n" +
" \"type294\"\n" +
" ],\n" +
" \"p1\": \"SOS\"\n" +
" }\n" +
" ],\n" +
" \"Item99\": [\n" +
" {\n" +
" \"attributeToRemove\": {\n" +
" \"someItem\": null\n" +
" },\n" +
" \"types\": [\n" +
" \"type19\",\n" +
" \"type29\"\n" +
" ],\n" +
" \"p1\": \"SOS\"\n" +
" }\n" +
" ]\n" +
"}"
@JvmStatic
fun main(args: Array<String>) {
val mapper = ObjectMapper()
mapper.visibilityChecker = mapper.serializationConfig.defaultVisibilityChecker.withCreatorVisibility(JsonAutoDetect.Visibility.ANY)
val answer = mapper.readValue(jsonString, Wrapper::class.java)
print(mapper.writeValueAsString(answer))
}
}
这篇关于如何使用Kotlin和杰克逊ObjectMapper从json中删除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!