使用jackson将pojo(对象列表)转换为java中的json

问题描述 投票:-1回答:1

我在将简单的JSON转换为POJO对象时遇到了问题。

这是我的代码:

public class Products {

private int id;
    private String type;
    private String description;
    private Double price;
    private String brand;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Double getPrice() {
        return price;
    }
    public void setPrice(Double price) {
        this.price = price;
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
}

我得到以下输出:

com.ObjectToJson.Product@b97c004
Object to Json --> {
"products" : null
}

我无法使用JACKSON API将JSON转换为Java对象。

拜托,任何人都可以帮我解决这个问题吗?

java json jackson
1个回答
0
投票

您尝试从对象创建JSON的代码在哪里?没有它,就很难说要解决什么问题。问题也可能来自您的Products类没有构造函数的事实。所以当你制造一个物体时什么都没有。初始化变量后应添加构造函数,如:

    public Products(){

    }

然后尝试从对象中创建JSON,这应该是这样的:

    Products p = new Products();
    ObjectMapper mapper = new ObjectMapper();
    String JSON = mapper.writeValueAsString(p); // to get json string 


    mapper.readValue(JSON, Products.class); // json string to obj

确保使用setter或getter设置Product的对象变量,或者通过向构造函数添加参数将它们初始化为值:

    public Products(String type, String description, Double price, 
    String brand){
        this.type = type;
        this.description = description; //etc etc...
    }
© www.soinside.com 2019 - 2024. All rights reserved.