【问题标题】:Getting null while parsing JSON using Jackson [duplicate]使用 Jackson 解析 JSON 时获取 null [重复]
【发布时间】:2023-03-12 10:04:01
【问题描述】:

我正在尝试使用 Jackson 解析 JSON,这是我的课程

@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer {
    private String name;
    
    public void setName(String n) {
        name = n;
    }
    public String getName() {
        return name;
    }
}

和跑步者类

public class jsontoObj {

    public static void main(String args[]) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
            String json = "{\n" +
                    "  \"customer\":\n" +
                    "  {\n" +
                    "    \"name\": \"John Doeyy\"\n" +
                    "  }\n" +
                    "}";

            Customer customer = mapper.readValue( json, Customer.class);
            System.out.println(customer.getName());
    }

}

setName 方法正在运行,但在customer.getName() 中获得了null。 我不想用moxy

【问题讨论】:

  • 你在一个对象中有一个对象。内部对象与您的 Customer 匹配,但您正在尝试解析 external 对象,该对象只有 customer 属性,而不是 name 属性。

标签: java json parsing null jackson


【解决方案1】:

根据您的映射,正确的 json 将是

String json = "{ \"name\": \"John Doeyy\" }";

我删除了嵌入的“客户”对象

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 2018-12-12
    • 2020-12-10
    • 2017-01-04
    • 2012-08-14
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多