I am trying to figure out how to create a nested array inside an array with Java. See below:
{
"fruit": [
"apple"
],
"color": [
[ <------ trying this!
"red",
"green"
] <------ trying this?
],
"edible": true
}
But I only managed to do this:
{
"fruit": [
"apple"
],
"color": [
"red",
"green"
],
"edible": true
}
And so far... this is the code I have:
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);
}
I am not sure if I should create an empty array list inside color or how this will fit into my code example. If someone could suggest what to do and I would prefer if you take/modify my code as appropriate as it would be easier/make more sense to me. Appreciate any help, thanks! :)
List<List<String>> color.colorproperty toList<List<String>>