gpt4 book ai didi

java - 如何使用Java在json数组中创建嵌套数组?

转载 作者:行者123 更新时间:2023-12-01 19:44:37 25 4
gpt4 key购买 nike

我试图弄清楚如何使用 Java 在数组内创建嵌套数组。见下文:

{
"fruit": [
"apple"
],
"color": [
[ <------ trying this!
"red",
"green"
] <------ trying this?
],
"edible": true
}

但我只做到了这一点:

{
"fruit": [
"apple"
],
"color": [
"red",
"green"
],
"edible": true
}

到目前为止...这是我的代码:

Class with logic to create the json object

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class FruitInventory {

public List<String> fruit;
public List<String> color;
private String edible;

public FruitInventory() {
}

public FruitInventory(List<String> fruit, List<String> color, String edible) {
this.fruit = fruit;
this.color = color;
this.edible = edible;
}

@JsonProperty("fruit")
public List<String> getfruit() {
return fruit;
}

@JsonProperty("fruit")
public void setfruit(List<String> fruit) {
this.fruit = fruit;
}

@JsonProperty("color")
public List<String> getcolor() {
return color;
}

@JsonProperty("color")
public void setcolor(List<String> color) {
this.color = color;
}

@JsonProperty("edible")
public String getedible() {
return edible;
}

@JsonProperty("edible")
public void setedible(String edible) {
this.edible = edible;
}

}

Method to print json

public static void main(String[] args) throws JsonProcessingException {
FruitInventory fruitInventory = new FruitInventory();
String json;
ObjectMapper mapper = new ObjectMapper();

List<String> fruit = new ArrayList<>();
fruit.add("apple")

List<String> color = new ArrayList<>();
color.add("red");
color.add("green");

fruitInventory.setColumnNames(fruit);
fruitInventory.setValues(color);

json = mapper.writeValueAsString(fruitInventory);
System.out.println(json);
}

我不确定是否应该在 color 内创建一个空数组列表,或者它如何适合我的代码示例。如果有人可以建议做什么,我更愿意您适本地采用/修改我的代码,因为这对我来说会更容易/更有意义。感谢任何帮助,谢谢! :)

最佳答案

更改public List<String> color;public List<List<String>> color;根据你的 json 结构。

填充它的逻辑:

List<String> color = new ArrayList<>();
color.add("red");
color.add("green");

fruitInventory.setValues( Arrays.asList(color));

关于java - 如何使用Java在json数组中创建嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53884099/

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