Let's say I want to directly read the object fruits from a Json file
and store it to the Fruit.class
. How should I do it?
{
"fruits": [
{ "name":"Apple", "price":"0.8"}
],
"vegetables": [
{ "name":"Carrot", "price":"0.4"}
]
}
My 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; }
}
What I've tried:
String file = "src/main/resources/basket.json";
String json = new String(Files.readAllBytes(Paths.get(file)));
objectMapper.readValue(json, Fruit.class);
Your json must match with what you try to convert. In your case you need
public class FruitWrapper {
private List<Fruits> fruits;
private List<Fruits> vegetables;
getters, setters...
}
Then this will work for you
FruitWrapper fruitWrapper = objectMapper.readValue(json, FruitWrapper.class);
Make a class called food:
public class Food {
private Fruit[] fruits;
private Fruit[] vegetables;
public Food() {
}
public Fruit[] getFruits() {
return fruits;
}
public Fruit[] getVegetables() {
return vegetables;
}
}
and then use:
objectMapper.readValue(json, Food.class);
after that you can get the fruits and vegetables from your food instance
We can write a little helper method, to convert raw string representation of the nested JSON array, to the Java list:
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;
}
}
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.