gpt4 book ai didi

java - 如何使用 Kotlin 和 jackson ObjectMapper 从 json 中删除属性

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:39 25 4
gpt4 key购买 nike

我想删除以下 JSON 中所有出现的“attributeToRemove”:

{
"Item994": [
{
"attributeToRemove": {
"someItem": null
},
"types": [
"type194",
"type294"
],
"p1": "SOS"
}
],
"Item99": [
{
"attributeToRemove": {
"someItem": null
},
"types": [
"type19",
"type29"
],
"p1": "SOS"
}
]
}

我尝试使用removeAll,但我保留了此错误:类型不匹配:推断类型为(JsonNode!) -> JsonNode!但是 (JsonNode!) -> 需要 boolean 值

有人可以建议如何解决这个问题吗?

这是我的代码:

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

关于java - 如何使用 Kotlin 和 jackson ObjectMapper 从 json 中删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com