gpt4 book ai didi

java - 使用 jackson 时跳过 JSON 中的第一级

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:02 25 4
gpt4 key购买 nike

我收到的 JSON 对象是这样的。

{  
"Question279":{
"ID":"1",
"Contents":"Some texts here",
"User":"John",
"Date":"2016-10-01"
}

我需要将 JSON 映射到以下 java bean。

public class Question {
@JsonProperty("ID")
private String id;

@JsonProperty("Contents")
private String contents;

@JsonProperty("User")
private String user;

@JsonProperty("Date")
private LocalDate date;

//some getters and setters are skipped...
}

另请注意,上述JSON对象Question279中的第一层并不总是相同的,它取决于用户提供的参数来获取JSON。我无法改变这种情况。

目前我正在使用类似的东西。

ObjectMapper mapper = new ObjectMapper();
String json = "{'Question279':{'ID':'1', 'Contents':'Some texts here', 'User':'John', 'Date':'2016-10-01'}"
Question question = mapper.readValue(json, Question.class);

但是它不起作用,当然,我得到了一个充满nullQuestion类。如何让它在这种情况下起作用?

最佳答案

试试这个会有什么帮助

ObjectMapper mapper = new ObjectMapper();

String json = "{\"Question279\":{\"ID\":\"1\", \"Contents\":\"Some texts here\", \"User\":\"John\", \"Date\":\"2016-10-01\"}}";

mapper.readTree( json ).fields().forEachRemaining( arg -> {

Question question = mapper.convertValue( arg.getValue(), Question.class );

System.out.println( question.getDate() );
} );

** 由于没有从 String 到 LocalDate 的默认转换,我在 Question.java 中将 LocalDate 日期 更改为 String date

关于java - 使用 jackson 时跳过 JSON 中的第一级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42341674/

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