gpt4 book ai didi

java - ObjectMapper 读取值

转载 作者:行者123 更新时间:2023-12-04 16:10:33 27 4
gpt4 key购买 nike

我加载一个资源文件json与文本格式

{
"sources": [{
"prop1": "1",
"prop2": "2"

},
{
"prop1": "1",
"prop2": "2"

},
],
"redirection": [{
"prop1": "1",
"prop2": "2"

}
]
}

我有一个具有此属性 prop1 和 prop2 的类

我想用 ObjectMapper 恢复一个列表类。什么方法?

此代码无效....

 Map<String, Object> mp =  mapper.readValue(jsonResource.getInputStream(),new TypeReference<Map<String, Object>>() {});
String sourceText= new ObjectMapper().readTree(jsonResource.getInputStream()).get("sources").asText();

mapper.readValue(sourceText, new TypeReference<List<MyClass>>(){});

谢谢你的帮助

最佳答案

在您的情况下,我会编写自定义 JsonDeserializer。还没有真正测试代码,但我认为思路很清楚:

    final MyClassDeserializer myClassDeserializer = new MyClassDeserializer();
final SimpleModule deserializerModule = new SimpleModule();
deserializerModule.addDeserializer(MyClass.class, myClassDeserializer);

final ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(deserializerModule);

JsonDeserializer 的代码:

    public class MyClassDeserializer extends JsonDeserializer<MyClass> {

@Override
public MyClass deserialize(final JsonParser jsonParser, final DeserializationContext context)
throws IOException {
final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
final JsonNode sourcesNode = node.get("sources");
if(node.isArray()) {
final ArrayNode arrayNode = (ArrayNode) node;
final Iterable<JsonNode> nodes = arrayNode::elements;
final Set<Source> set = StreamSupport.stream(nodes.spliterator(), false)
.map(mapper)
.collect(Collectors.toSet());
...
}

...
}

关于java - ObjectMapper 读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42691591/

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