I have the following JSON output that I want to generate.
**JSON Output:**
{
"ingredients": {
"main": ["flour", "water", "egg"],
"optional": ["olives", "salami"]
}
}
I tried to create the following classes but I am having some difficulty to do the following:
Am I even doing it the right way??
public class Pizza { private Ingredients[] fIngredients; @JsonProperty("ingredients") public Ingredients[] getIngredients() { return fIngredients; } public void setIngredients(Ingredients ingredients) { fIngredients = ingredients; } } public class Ingredients { private String[] fFoods; @JsonProperty("????") // how do i put a dynamic name here? public String[] getFoods() { return fFoods; } public void addFoods(List<String> foodsList) { String[] array = foodsList.toArray(foodsList.size()); fFoods = ArrayUtils.addAll(fFoods, array); } }
In order to have dynamic properties, you can use Map
type for your properties. So you can have your code like this:
public class Pizza {
private Map<String, List<String>> ingredients = new HashMap();
public Map<String, List<String>> getIngredients() {
return ingredients;
}
public void addIngredient(String name, List<String> values) {
ingredients.put(name, values);
}
public static void main(String[] args) {
Pizza pizza = new Pizza();
pizza.addIngredient("main", Arrays.asList("flour", "water", "egg"));
pizza.addIngredient("optional", Arrays.asList("olives", "salami"));
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(pizza));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.