![](/img/trans.png)
[英]Use Jackson Objectmapper configured by Spring boot in Hibernate
[英]How to use ObjectMapper in JUnitTests - Spring Boot app
我在Spring Boot應用程序的JUnit測試中使用ObjectMapper有問題。
傑克遜映射POJO:
public Repository() {
@JsonProperty(value="fullName")
public String getFullName() {
return fullName;
}
@JsonProperty(value="full_name")
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonProperty(value = "cloneUrl")
public String getCloneUrl() {
return cloneUrl;
}
@JsonProperty(value = "clone_url")
public void setCloneUrl(String cloneUrl) {
this.cloneUrl = cloneUrl;
}
@JsonProperty(value="stars")
public int getStars() {
return stars;
}
@JsonProperty(value="stargazers_count")
public void setStars(int stars) {
this.stars = stars;
}
...
}
JUnit測試:
@Autowired
private ObjectMapper objectMapper;
@Test
public void testWithMockServer() throws Exception{
Repository testRepository = new Repository();
testRepository.setCloneUrl("testUrl");
testRepository.setDescription("testDescription");
testRepository.setFullName("test");
testRepository.setStars(5);
String repoString = objectMapper.writeValueAsString(testRepository);
...
}
從testRepository
創建String之后,我看到不是所有字段testRepository
設置-僅是描述,不需要任何其他JsonProperty映射。 這是因為未考慮來自Repository
類的@JsonProperty
。 你知道怎么解決嗎? 在控制器中,一切正常。
restTemplate.getForObject(repoUrlBuilder(owner,repository_name),Repository.class);
(這是這里答案的解釋)。
僅當您使用其他屬性並適當委托時,此方法才有效。 使用您的代碼,Jackson會為同一屬性找到兩個名稱,然后選擇一個:大概是setter方法上的名稱,因為控制器中的解組對您有用。
您需要兩個名稱不同且值相同的屬性。 例如:
@JsonProperty(value="fullName")
public String getFullName() {
return fullName;
}
@JsonProperty(value="full_name")
public void setFull_Name(String fullName) { // Different property name here
this.fullName = fullName;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.