代码之家  ›  专栏  ›  技术社区  ›  Saffik

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

  •  0
  • Saffik  · 技术社区  · 7 年前

    我试图弄清楚如何使用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 或者这将如何适合我的代码示例。如果有人能建议我该怎么做,我更希望你能适当地使用/修改我的代码,因为这对我来说更容易/更有意义。感谢您的帮助,谢谢!:)

    1 回复  |  直到 7 年前
        1
  •  3
  •   Aditya Narayan Dixit    7 年前

    改变 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));