2

假设我想直接从 a 读取对象 fruitsJson file并将其存储到Fruit.class. 我该怎么做?

{
  "fruits": [
    { "name":"Apple", "price":"0.8"}
  ],
  "vegetables": [
    { "name":"Carrot", "price":"0.4"}
  ]
}

我的模型class

public class Fruit {
    private String name;
    private double price;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price= price; }
}

我试过的:

String file = "src/main/resources/basket.json";
String json = new String(Files.readAllBytes(Paths.get(file)));
objectMapper.readValue(json, Fruit.class);
4

3 回答 3

6

您的 json 必须与您尝试转换的内容相匹配。在您的情况下,您需要

public class FruitWrapper {

   private List<Fruits> fruits;
   private List<Fruits> vegetables;

   getters, setters...

   }

那么这对你有用

 FruitWrapper fruitWrapper =  objectMapper.readValue(json, FruitWrapper.class);
于 2021-03-27T19:14:13.770 回答
1

创建一个名为 food 的类:

public class Food {
    private Fruit[] fruits;
    private Fruit[] vegetables;
    
    public Food() {
    }

    public Fruit[] getFruits() {
        return fruits;
    }

    public Fruit[] getVegetables() {
        return vegetables;
    }
}

然后使用:

objectMapper.readValue(json, Food.class);

之后你可以从你的食物实例中获取水果和蔬菜

于 2021-03-27T19:17:26.410 回答
0

我们可以编写一个小助手方法,将嵌套 JSON 数组的原始字符串表示形式转换为 Java 列表:

public class EntryPoint {

    public static void main(String[] args) throws Exception {
        String json = new String(Files.readAllBytes(Paths.get("src/main/resources/basket.json")));

        //maybe better to use more generic type Product? as fruits and vegs have same structure
        List<Fruit> fruits = getNestedJSONArray(json, "fruits");
        List<Fruit> vegetables = getNestedJSONArray(json, "vegetables");

    }

    private static List<Fruit> getNestedJSONArray(String json, String key) throws Exception {
        List<Fruit> fruits = new ArrayList<>();
        new ObjectMapper().readTree(json)
                .get(key)
                .forEach(e -> {
                    Fruit tmpf = new Fruit();
                    tmpf.setName(e.get("name").textValue());
                    tmpf.setPrice(e.get("price").asDouble());
                    fruits.add(tmpf);
                });
        return fruits;
    }
}
于 2021-03-27T19:30:45.890 回答