gpt4 book ai didi

java - 如何将嵌套 JSON 映射到简单对象?

转载 作者:行者123 更新时间:2023-12-01 20:00:09 28 4
gpt4 key购买 nike

我想映射此 JSON 数据:

{"information":{
"type": "typeA",
"date": "2018-01-15 12:11:53",
"user":{
"name": "John"
"lastName": "Doe"
}
}}

到这个java对象:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InformationModel {
private String name;
private String lastName;

private String type;
private String date;
}

但是它失败了并且所有值都是null。我尝试在 type 变量上方添加 @JsonProperty("information.type") 但没有成功。

是否可以反序列化 JSON,以便它仅映射到(这个)一个类?

编辑:我正在使用 Spring StreamListener 进行如下映射:

@StreamListener(value = Sink.INPUT)
public void on(InformationModel message) throws IOException {
// some code using message
}

最佳答案

我必须承认我对 Spring 了解不多,所以我的答案可能不太准确,但既然你已经用 java 标记了你的问题,这是我的答案(使用 org.json):

String jsonString = "{\"information\":{\"type\": \"typeA\",\"date\": \"2018-01-15 12:11:53\",\"user\":{\"name\": \"John\",\"lastName\": \"Doe\"}}}";

JSONObject o = new JSONObject(jsonString);

JSONObject obj = o.getJSONObject("information");
String date = obj.getString("date");
//map whatever you want to map here.
System.out.println(date);

显然这是非常基本的,但你明白了。您也许可以使用 JSONArray 实现相同的目的。

希望对你有帮助!

关于java - 如何将嵌套 JSON 映射到简单对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48263689/

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