[英]How to map nested JSON into object model in SpringBoot
Hi everyone I have a nested JSON that I have to map into 3 object models.大家好,我有一个嵌套的 JSON,我必须将 map 放入 3 个 object 模型中。 I have to create
CarResponse
, Car
and CarValue
models.我必须创建
CarResponse
、 Car
和CarValue
模型。
Here is my JSON file:这是我的 JSON 文件:
{
"car": [
{
"shop": "Audi Germany",
"date": 1573599600000,
"values": [
{
"name": "Audi Xl",
"age": "2020",
"country": "Germany"
},
{
"name": "Audi i",
"age": "2021",
"country": "France"
},
{
"name": "Bmw Xl",
"age": "2020",
"country": "Spain"
},
{
"name": "Citroen",
"age": "1990",
"country": "France"
}
}]
}
So I created 3 modals.所以我创建了 3 个模态。
public class CarResponse {
List<Car> quotes = new ArrayList<Car>();
//Getters setters
}
public class Car {
private String shop;
private String date;
//Getters setters and toString
}
public class CarValue {
private String name;
private String country;
private Long age;
//Getters setters and toString
}
I am not sure if this is a right way.我不确定这是否是正确的方法。 Because when I try to write a test on it, I am not sure where to start.
因为当我尝试在上面写一个测试时,我不知道从哪里开始。
I created DataLoader
class to read from JSON.我创建了
DataLoader
class 来读取 JSON。
@Service
public class DataLoader {
@Value("${DataLoader.url}") private String urlStr;
public QuoteResponse load() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(urlStrl, QuoteResponse.class);
}
}
And how should I write a test for it now?我现在应该如何为它编写测试?
You almost have that with a couple of changes, CarResponse
is a root JSON with property car
which is List<Car>
type您几乎可以通过一些更改来实现,
CarResponse
是一个根 JSON,其属性car
是List<Car>
类型
public class CarResponse {
List<Car> car = new ArrayList<Car>();
//Getters setters
}
And then each Car
has shop
, date
and values
List然后
Car
都有shop
, date
和values
List
public class Car {
private String shop;
private String date;
private List<CarValue> values
//Getters setters and toString
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.