[英]Not able to map Json to java Object using Jackson and lombok
POJO:
import lombok.Data;
@Data
public class CCMTRequest {
private MOEH cch;
private String filler1;
private CCMTCCD ccd;
private String uPwName;
}
@Data
public class MOEH {
private String c;
private int z;
private String dType;
}
@Data
public class CCMTCCD {
private dTime time;
private int x;
}
@Data
public class dTime {
private String dTime;
}
測試Class:
public class TestJacksonParser {
@Test
void load_jsonToPOJO() {
ObjectMapper mapper = new ObjectMapper();
ClassLoader load = this.getClass().getClassLoader();
File file = new File(load.getResource("request.json").getFile());
CCMTRequest req = null;
try {
req = mapper.readValue(file, CCMTRequest.class);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
System.out.println("\nRequest: " + req);
}
}
請求.json:
{
"cch" : {
"c" : "C",
"z" : 4678,
"dType" : "dtype"
},
"filler1" : "random filler1",
"ccd" : {
"time" : {
"dTime" : "4:35"
},
"x" : 34567
},
"uPwName" : "uPwName"
}
錯誤:
無法識別的字段“dType”(類 com.spring.mapstruct.test.MOEH),未標記為可忽略(3 個已知屬性:“z”、“c”、“dtype”])在 [來源:(文件); 行:5,列:14](通過參考鏈:com.spring.mapstruct.test.CCMTRequest["cch"]->com.spring.mapstruct.test.MOEH["dType"])
索取:null
現在,當我將測試 class 更新為:
public class TestJacksonParser {
@Test
void load_jsonToPOJO() {
ObjectMapper mapper = new ObjectMapper();
//ignore Unknown JSON Fields
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ClassLoader load = this.getClass().getClassLoader();
File file = new File(load.getResource("request.json").getFile());
CCMTRequest req = null;
try {
req = mapper.readValue(file, CCMTRequest.class);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
System.out.println("\nRequest: " + req);
}
}
我得到 output 作為:
請求:CCMTRequest(cch=MOEH(c=C, z=4678, dType=null), filler1=random filler1, ccd=CCMTCCD(time=dTime(dTime=4:35), x=34567), uPwName=null)
那么 jackson 如何與 lombok 一起工作,屬性“dType”和“uPwName”是否存在問題?
首先,下次請提供更好的示例而不是隨機名稱屬性。 這很混亂。
你的問題是因為 lombok 為像“uPwName”這樣的屬性生成了 getter 和 setter 變成了“getUPwName()”和“setUPwName()”。 jackson 讀作“getuPwName”和“setuPwName”;
該庫都對 getter 和 setter 使用不同的命名約定。
有兩種方法可以解決這個問題:
ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.