java - 如何使用 Kotlin 和 jackson ObjectMapper 从 json 中删除属性
问题描述
我想删除以下 JSON 中所有出现的“attributeToRemove”:
{
"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
谁能建议如何解决这个问题?
这是我的代码:
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") }
}
解决方案
将 jsonString 转换为 Object,忽略要删除的字段,然后映射回 jsonString:
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
class Item99 {
var p1: String? = null
var types: Array<String>? = null
}
class Item994 {
var p1: String? = null
var types: Array<String>? = null
}
class Wrapper (
@SerializedName("Item99")
var item99: Array<Item99>?,
@SerializedName("Item994")
var item994: Array<Item994>?
)
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 gson = Gson()
val wrapper = gson.fromJson(jsonString,Wrapper::class.java)
println(gson.toJson(wrapper))
}
}
输出将如下所示:
{"Item99":[{"p1":"SOS","types":["type19","type29"]}],"Item994":[{"p1":"SOS","types":[ "type194","type294"]}]}
推荐阅读
- c# - 从列表中获取其他值
- python - 用于 VS 代码的 SSH_INTERPRETER
- c# - 自动化 .net 框架网站
- c# - EF6 Linq to Sql 列别名超过 30 个字符
- visual-studio-code - 使用 vim 扩展时禁用复制/粘贴的键盘快捷键
- c# - 为什么这个 ListView 不绑定到这个列表?
- vb.net - Linq:查询加入和等于(变量)不起作用
- python - 使用嵌套列表索引时 Pythonic 交换导致索引错误
- css - Firefox v42+ 是否支持 CSS 网格?
- c# - 使用 SAS url 将 MSI 文件放入 Azure 存储