gpt4 book ai didi

java - 嵌套 JSON 映射到 Jackson,其中 key 是动态的

转载 作者:行者123 更新时间:2023-12-01 10:40:29 25 4
gpt4 key购买 nike

我希望将嵌套 JSON 结构映射到 Jackson 中,其中对象是动态 ID 的对象。

{ 
"id1": {
"prop": true
},
"id2": {
"prop": true
},
"id3": {
"prop": true
}
}

我目前有以下 Jackson POJO:

package com.uk.jacob.containerdroid;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;

import java.util.HashMap;
import java.util.Map;

public class Container {
private Map<String, ContainerDetails> properties = new HashMap<>();

public class ContainerDetails {
private boolean prop;

public boolean getProp() {
return prop;
}

public void setProp(boolean prop) {
this.prop = prop;
}
}

@JsonAnySetter
public void add(String key, ContainerDetails value) {
properties.put(key, value);
}

@JsonAnyGetter
public Map<String, ContainerDetails> getProperties() {
return properties;
}

@Override
public String toString() {
return "Containers {" +
", properties=" + properties.toString() +
'}';
}
}

适用于静态属性数据,但不适用于嵌套 JSON。

我收到错误:

12-23 22:32:41.628  14098-14098/? W/System.err﹕ at [Source: { "test": { "prop": true } }; line: 1, column: 13] (through reference chain: com.uk.jacob.containerdroid.models.Container["test"])

如何操作以上内容以正确映射?

最佳答案

看来你只是想要一个Map<String, Foo> ,其中 Foo 定义为

public class Foo {
private boolean prop;

// getter, setter omitted
}

完整的工作示例:

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Foo {
private boolean prop;

public boolean isProp() {
return prop;
}

public void setProp(boolean prop) {
this.prop = prop;
}

@Override
public String toString() {
return "Foo{" +
"prop=" + prop +
'}';
}

public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{ \n" +
" \"id1\": {\n" +
" \"prop\": true\n" +
" },\n" +
" \"id2\": {\n" +
" \"prop\": true\n" +
" },\n" +
" \"id3\": {\n" +
" \"prop\": true\n" +
" }\n" +
" }";
Map<String, Foo> map = mapper.readValue(json, new TypeReference<Map<String, Foo>>() {
});

System.out.println("map = " + map);
}
}

关于java - 嵌套 JSON 映射到 Jackson,其中 key 是动态的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34444408/

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