[英]how to build java Pojo for Json in springboot
I have following Json and want to map this json as java pojo using spring webclient mono response. 在这个 json 中,键 data-1 和 en 不是常数,并且不断变化。 例如,它可以是 data-2 和 fr 或 data-3 和它。
{
"data": {
"attributes": {
"data-1": {
"en": [
{
"id": 1,
"code": "GI",
"order": 10
},
{
"id": 2,
"code": "TH",
"order": 10
}
]
}
}
}
}
DTO结构:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ListData {
private Map<String, Attributes> data;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Attributes {
private Map<String, Map<String, MyList>> attributes;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyList {
private List<Entry> entryList;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Entry {
private String id;
private String code;
private String order;
}
这是反序列化 json 的 webclient。
return WebClient.create("test.com")
.get()
.uri(getTestUri())
.header(HttpHeaders.ACCEPT, Constants.ACCEPT_TYPE)
.retrieve()
.bodyToMono(ListData.class)
.block();
以下是错误:
org.springframework.core.codec.CodecException: Type definition error: [simple type, class com.test.ListAttributes]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.test.ListAttributes` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
有人可以帮我解决这个问题,如何解决。
{
"data": {
"attributes": {
"data-1": {
"en": [
{
"id": 1,
"code": "GI",
"order": 10
},
{
"id": 2,
"code": "TH",
"order": 10
}
]
}
}
}
}
“data-1”和“en”作为变量键意味着需要一个双重嵌套的Map
。 内部 map 将字符串映射到对象List
(在您的特定情况下为Entry
对象)。
因此,上述 JSON 的结构/类型映射到 Java 类型:
class Container {
public Data data;
public Container() {}
}
class Data {
public Map<String, Map<String, List<Entry>>> attributes;
public Data() {}
}
class Entry {
public long id;
public String code;
public long order;
public Enrty() {}
}
确保您的类型是默认可构造的,并且其字段可以由 Jackson 设置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.