简体   繁体   中英

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

I'm facing a problem while converting simple JSON to POJO object.

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.

Please, can anyone help me out on this?

Where is the code where you try to create the JSON from your object? 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. 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:

    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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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