作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
要求:
问题:步骤 1 和 2 没问题。当将 POJO 转换回 JsonNode 时,我无法在 POJO 字段名称中获取它。谁能建议一种方法来实现这个?
下面是我的代码
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyPOJO {
@JsonProperty("Firstname")
private String name;
@JsonProperty("Country")
private String nationality;
private String state;
//getters and setters
}
逻辑
ObjectMapper map = new ObjectMapper();
JsonNode root =map.readTree(new Main().getResorceFile());
List<MyPOJO> myList = new ArrayList<MyPOJO>();
for(JsonNode each : root){
MyPOJO myPOJO = new MyPOJO();
myPOJO= map.readValue(each.toString(),MyPOJO.class);
System.out.println(myPOJO.toString());
myList.add(myPOJO);
}
for(MyPOJO p : myList){
JsonNode node = map.convertValue(p,JsonNode.class);
System.out.println((node.toString()));
}
Json 文件
{
{
"Firstname":"Tez",
"Lastname":"Morris",
"Country":"US"
},
{
"Firstname":"Kip",
"Lastname":"Lee",
"Country":"US"
},
{
"Firstname":"Pam",
"Lastname":"Carr",
"Country":"US"
},
{
"Firstname":"lin",
"Lastname":"Dale",
"Country":"US"
}
}
输出:
Main{name='Tez', nationality='US', state='null'}
Main{name='Kip', nationality='US', state='null'}
Main{name='Pam', nationality='US', state='null'}
Main{name='lin', nationality='US', state='null'}
{"state":null,"Firstname":"Tez","Country":"US"}
{"state":null,"Firstname":"Kip","Country":"US"}
{"state":null,"Firstname":"Pam","Country":"US"}
{"state":null,"Firstname":"lin","Country":"US"}
预期输出
Main{name='Tez', nationality='US', state='null'}
Main{name='Kip', nationality='US', state='null'}
Main{name='Pam', nationality='US', state='null'}
Main{name='lin', nationality='US', state='null'}
{"state":null,"name":"Tez","nationality":"US"}
{"state":null,"name":"Kip","nationality":"US"}
{"state":null,"name":"Pam","nationality":"US"}
{"state":null,"name":"lin","nationality":"US"}
最佳答案
解决方案是将 @JsonProperty
放在具有不同值的 getter 和 setter 上,例如:
[…]
private String nationality;
@JsonProperty("nationality")
public String getNationality() {
return nationality;
}
@JsonProperty("Country")
public void setNationality(String nationality) {
this.nationality = nationality;
}
[…]
getter 执行序列化,setter 执行反序列化。
关于java - 使用 POJO 字段名将 POJO 转换为 JsonNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518793/
我是一名优秀的程序员,十分优秀!