java - 如何使用Java在json中的数组内创建嵌套数组?
问题描述
我试图弄清楚如何使用 Java 在数组中创建嵌套数组。见下文:
{
"fruit": [
"apple"
],
"color": [
[ <------ trying this!
"red",
"green"
] <------ trying this?
],
"edible": true
}
但我只能做到这一点:
{
"fruit": [
"apple"
],
"color": [
"red",
"green"
],
"edible": true
}
到目前为止......这是我拥有的代码:
具有创建 json 对象的逻辑的类
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;
}
}
打印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
或者这将如何适合我的代码示例。如果有人可以建议做什么,我希望您适当地采用/修改我的代码,因为这对我来说更容易/更有意义。感谢任何帮助,谢谢!:)
解决方案
根据您的 json 结构更改public List<String> color;
为。public List<List<String>> color;
填充它的逻辑:
List<String> color = new ArrayList<>();
color.add("red");
color.add("green");
fruitInventory.setValues( Arrays.asList(color));
推荐阅读
- css - 如何以角度为 ng-select 自定义 css?
- avaloniaui - 如何在代码中制作与 Avalonia UI 兼容的位图?
- python - 我发现很难修复使字典项无法使用 json 文件调用的错误
- c# - 即使在等待元素启用后也出现 ElementNotInteractableException
- java - ItemkeyedDataSource.LoadInitialCallback onResult() 没有做任何事情
- javascript - React,在主函数之外声明的 if else 比较函数中的错误
- javascript - 制表符:使用带有链接格式化程序的图标
- c# - System.IO.IOException: '该进程无法访问该文件,因为它正被另一个进程使用
- laravel - laravel 的 AppServiceProvider 中未设置路由
- javascript - Vue.js 试图通过计算中的 ID 获取 DOM 元素返回 null