我正在尝试读取我的 .json 文件。是VehicleRepository
类。
"{\"vehicles\":[{\"id\":\"9467d079-4502-4dba-9d23-b8506dfc7ef4\",\"plate\":\"ghghghhg\",\"manufacturer\":\"Alfa Romeo\",\"model\":\"hgghgh\",\"color\":\"Amarelo\"}]}"
这是错误:
com.fasterxml.jackson.databind.exc.MismatchedInputException:无法构造
VehicleRepository
的实例(尽管存在至少一个创建者):无法构造VehicleRepository
的实例(尽管至少存在一个创建者) :没有[[Source:(File);行:1,列:1]
我要使用以下方法来创建.json
文件:
repository.vehicles = new ArrayList<Vehicle>();
repository.vehicles.add(vehicle);
json = mapper.writeValueAsString(repository);
ObjectMapper write = new ObjectMapper();
write.writeValue(new File("Database//Vehicles.json"), json);
要读取.json
文件,我正在使用此文件:
VehicleRepository newRepository = mapper.readValue(new File("Database\\Vehicles.json"), VehicleRepository.class);
并且在上面的行中发生了错误。
这是我的Vehicle
班:
public class Vehicle {
private String id;
private String plate;
private String manufacturer;
private String model;
private String color;
public Vehicle() {}
public Vehicle(String plate, String manufacturer, String model, String color) {
this.id = UUID.randomUUID().toString();
this.plate = plate;
this.manufacturer = manufacturer;
this.model = model;
this.color = color;
}
public Vehicle(String id, String plate, String manufacturer, String model, String color) {
this.id = id;
this.plate = plate;
this.manufacturer = manufacturer;
this.model = model;
this.color = color;
}
public String getId() {
return id;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
这是我的VehicleRepository
班:
public class VehicleRepository {
List<Vehicle> vehicles;
public VehicleRepository() {
}
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
}
有人可以帮我吗?
答案 0 :(得分:1)
代码中的问题是,您首先要将对象转换为String并将该String作为JSON写入文件。
您可以使用以下方法将对象写入文件中:
write.writeValue(new File("Vehicles.json"), repository);
结果将是正确的json:
{"vehicles":[{"id":"9467d079-4502-4dba-9d23-b8506dfc7ef4","plate":"ghghghhg","manufacturer":"Alfa Romeo","model":"hgghgh","color":"Amarelo"}]}
这可以通过您已经拥有的代码完美地阅读:
VehicleRepository newRepository = mapper.readValue(new File("Vehicles.json"), VehicleRepository.class);