gpt4 book ai didi

java - 嵌套 json 的模型类

转载 作者:行者123 更新时间:2023-11-30 10:40:43 25 4
gpt4 key购买 nike

我想解析一个嵌套的 json,其中父键包含两个不同的嵌套键对象(不是可以在列表中抽象和序列化的单个模型)。

此示例 Json 的正确 Java 模型(对应的类)是什么?

{
"name" : "Jack",
"surname" : "Hopper",
"address" : "711-2880 Nulla St. Mankato Mississippi 96522",
"FatherKey" :
{
"ChildKeyNo1" :
{
"defaultKey" : "2_s_g",
"key1" : "4_s_g",
"key2" : "2_s_g"
},
"ChildKeyNo2" :
{
"defaultKey" : "4_s_g",
"key1" : "6_s_g",
"key2" : "7_s_g"
}
}
}

我想出了:

public class MainJsonConfiguration{
private String name;
private String surname;
private String address;
private FatherKey fatherKey;

public MainJsonConfiguration(String name, String surname, String address, String fatherKey){
this.name = name;
this.surname = surname;
this.address = address;
this.fatherKey = new FatherKey(new ChildKey(), new ChildKey());
}
}

public class FatherKey{

private ChildKey childKey1;
private ChildKey childKey2;

public FatherKey(ChildKey childKey1, ChildKey childKey2){
this.childKey1 = childKey1;
this.childKey2 = childKey2;
}
}

public class ChildKey{

private String defaultKey;
private String key1;
private String key2;

public ChildKey(){
}
}

但它闻起来有鱼腥味......

有什么建议吗?

非常感谢

最佳答案

您可以使用 FasterXML Jackson使用注释 JsonProperty 来定义要注入(inject)构造函数的属性的名称。

你的类(class)看起来像这样:

public class MainJsonConfiguration{
private String name;
private String surname;
private String address;
private FatherKey fatherKey;

public MainJsonConfiguration(@JsonProperty("name") String name,
@JsonProperty("surname") String surname,
@JsonProperty("address") String address,
@JsonProperty("FatherKey") FatherKey fatherKey){
this.name = name;
this.surname = surname;
this.address = address;
this.fatherKey = fatherKey;

}
}

public class FatherKey{

private ChildKey childKey1;
private ChildKey childKey2;

public FatherKey(@JsonProperty("ChildKeyNo1") ChildKey childKey1,
@JsonProperty("ChildKeyNo2") ChildKey childKey2){
this.childKey1 = childKey1;
this.childKey2 = childKey2;
}
}

public class ChildKey{

private String defaultKey;
private String key1;
private String key2;

public ChildKey(@JsonProperty("defaultKey") String defaultKey,
@JsonProperty("key1") String key1,
@JsonProperty("key2") String key2){
this.defaultKey = defaultKey;
this.key1 = key1;
this.key2 = key2;
}
}

这是解析 JSON 的代码:

ObjectMapper mapper = new ObjectMapper();
MainJsonConfiguration configuration = mapper.readValue(
jsonString, MainJsonConfiguration.class
);

关于java - 嵌套 json 的模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38792203/

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