有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Jackson从Json文件读取特定对象

假设我想直接从Json 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);

共 (3) 个答案

  1. # 1 楼答案

    我们可以编写一个小助手方法,将嵌套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;
        }
    }
    
  2. # 2 楼答案

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

    public class FruitWrapper {
    
       private List<Fruits> fruits;
       private List<Fruits> vegetables;
    
       getters, setters...
    
       }
    

    那么这对你有用

     FruitWrapper fruitWrapper =  objectMapper.readValue(json, FruitWrapper.class);
    
  3. # 3 楼答案

    制作一个名为“食物”的课程:

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

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