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