gpt4 book ai didi

java - 如何制作具有动态值的@JSONProperty?

转载 作者:行者123 更新时间:2023-12-02 09:40:46 25 4
gpt4 key购买 nike

我想要生成以下 JSON 输出。

**JSON Output:**
{
"ingredients": {
"main": ["flour", "water", "egg"],
"optional": ["olives", "salami"]
}
}

我尝试创建以下类,但执行以下操作时遇到一些困难:

  1. 如何创建动态 JSONProperty,如“主要”和“可选”可以是动态值。
  2. 如何返回字符串数组?
  3. 我的做法正确吗?

      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);
    }
    }

最佳答案

为了拥有动态属性,您可以为属性使用Map类型。所以你可以有这样的代码:

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));
}
}

关于java - 如何制作具有动态值的@JSONProperty?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57095336/

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