我有一个 json 对象
{ "Children": { "name": "rahul", "value": 1231, "calculated": false } }
并且需要转换成一个 java bean 类。但是在编写代码并打印 java 对象之后,它应该以 java 对象的形式打印整个 json 对象,但它只打印里面有 null 的 Children。它没有访问 Children 属性。
class Children {
private String name;
private int value;
private boolean calculated;
public Children(String name, int value, boolean calculated) {
this.name = name;
this.value = value;
this.calculated = calculated;
}
public Children() {
}
// Add getters and setters for the fields...
public String getName() {
return name;
}
public int getValue() {
return value;
}
public boolean isCalculated() {
return calculated;
}
public void setName(String name) {
this.name = name;
}
public void setValue(int value) {
this.value = value;
}
public void setCalculated(boolean calculated) {
this.calculated = calculated;
}
@Override
public String toString() {
return "Children{" +
"name='" + name + '\'' +
", value=" + value +
", calculated=" + calculated +
'}';
}
}
class Itemcontainer extends Children
{
Children children;
public Children getChildren() {
return children;
}
public void setChildren(Children children) {
this.children = children;
}
@Override
public String toString() {
return "Itemcontainer{" +
"children=" + children +
'}';
}
}
public class Main {
public static void main(String[] args) throws IOException {
ObjectMapper object = new ObjectMapper();
object.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Itemcontainer itemcontainer;
try {
itemcontainer = object.readValue(new File("E:\\json_home_impl\\saudip_3.json"),Itemcontainer.class );
}
catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(itemcontainer.toString());
}
}
得到输出为
{Children= null}
,正如我所期望的那样 {"Children" { "name"= "rahul", "value"= 1231, "calculated"= false}}
存在大小写问题:在您的 json 中,您使用名称“Children”作为您的属性,但您的映射期望该字段被命名为“children”。由于您不会因未知属性而失败,因此它会被忽略。
选项:要么将 JSON 更改为具有小写的“children”属性,要么将 @JsonProperty 注释添加到您的映射中:
class Itemcontainer extends Children
{
@JsonProperty("Children")
Children children;
public Children getChildren() {
return children;
}
public void setChildren(Children children) {
this.children = children;
}
@Override
public String toString() {
return "Itemcontainer{" +
"children=" + children +
'}';
}
}