Skip to content

How to read value from JSON with Jackson Java

I have a JSON file:

{
    "param": {
        "rows": 1,
        "columns": "4"
    },
    "items": [{
        "name": "A",
        "amount": 33,
        "price": "43"
    }, {
        "name": "B",
        "amount": 43,
        "price": "2"
    }, {
        "name": "C",
        "amount": 45,
        "price": "1"
    }, {
        "name": "D",
        "amount": 543,
        "price": "55" 
   }]
}

I want to get the items separately. I try to do, but the result did null:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Items item; // only items
item =  objectMapper.readValue(new File("D:/example/file.json"), Items.class);
System.out.println(item.getAmount());

This is class for Items:

public class Items {
    private String name;
    private String amount;
    private double price;

    public Items() {
        super();
    }

    //constructor

    //getters and setters
}

What I do wrong? how correctly read value from items?

Answer

You didn’t handle the JSON array – items – properly, so as I commented under OP, all what you need to do is to rename original class Items to Item and create another class Items as follows, and the Jackson library will do the rest for you:

public class Item {
    private String name;
    private String amount;
    private double price;

    // general getters/setters
}

public class Items {
    private List<Item> items;

    // general getter/setter
}

Then you can deserialize the JSON string with your code snippet:

Items items = objectMapper.readValue(new File("D:/example/file.json"), Items.class);
System.out.println(items.get(0).getAmount());