![](/img/trans.png)
[英]Read Object Array From JSON Array in a JSON file (using Jackson)
[英]How to read a specific object from a Json file using Jackson
假设我想直接从Json file
中读取 object 水果并将其存储到Fruit.class
。 我该怎么做?
{
"fruits": [
{ "name":"Apple", "price":"0.8"}
],
"vegetables": [
{ "name":"Carrot", "price":"0.4"}
]
}
我的 model 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);
您的 json 必须与您尝试转换的内容匹配。 在您的情况下,您需要
public class FruitWrapper {
private List<Fruits> fruits;
private List<Fruits> vegetables;
getters, setters...
}
那么这对你有用
FruitWrapper fruitWrapper = objectMapper.readValue(json, FruitWrapper.class);
制作一个名为 food 的 class:
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);
之后你可以从你的食物实例中获取水果和蔬菜
我们可以编写一个小助手方法,将嵌套 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.