简体   繁体   English

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

[英]Convert pojo (list of object) to json in java using jackson

I'm facing a problem while converting simple JSON to POJO object.我在将简单的 JSON 转换为 POJO 对象时遇到问题。

This is my code:这是我的代码:

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;
    }
}

Im getting below as output:我在下面作为输出:

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

I am not able to convert JSON to/from Java Objects using JACKSON API.我无法使用 JACKSON API 将 JSON 转换为 Java 对象/从 Java 对象转换。

Please, can anyone help me out on this?拜托,有人可以帮我解决这个问题吗?

Where is the code where you try to create the JSON from your object?您尝试从对象创建 JSON 的代码在哪里? Without it, it will be hard to say what to fix.没有它,很难说要修复什么。 The problem may also be coming from the fact that your Products class has no constructor.问题也可能来自您的 Products 类没有构造函数的事实。 So when you make an object its nothing.所以当你让一个对象什么都不是。 You should add a constructor after you initialize your variables like:您应该在初始化变量后添加一个构造函数,例如:

    public Products(){

    }

Then try making your JSON from the object, which should be something like:然后尝试从对象制作你的 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

Be sure to set your Product's object variables using setters or getters, or to initialize them to values by adding parameters to your constructor:确保使用 setter 或 getter 设置产品的对象变量,或者通过向构造函数添加参数来将它们初始化为值:

    public Products(String type, String description, Double price, 
    String brand){
        this.type = type;
        this.description = description; //etc etc...
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM