Pages

Wednesday, 16 September 2015

Obtaining the name of the key in fasterxml

In this blog, I have just presented a simple sample of using fasterxml API to parse JSON data. This shows you how you can get the name of the key within a JSON object.

Suppose, you have a JSON sample as below:

{
"data": {
        "itemId": 1,
        "itemName": "Table",
        "price": 400,
        "dimensions": {
            "length": 5.0,
            "width": 10.0,
            "height": 4.0
        },
        "warehouseLocation": {
            "latitude": -48.45,
            "longitude": 20.5
        },
 "contact": [{
  "name": "Alison",
  "phone": "6454666"
 },{
  "name": "Simon",
  "phone": "6433666"
 }]
    }
}

Now, using java, if you are interested in obtaining itemName's contents, you would write code as below using fasterxml:

            ObjectMapper _MAPPER = new ObjectMapper();
            JsonNode node = _MAPPER.readTree(reader);
            JsonNode dataNode = node.get("data");
            Iterator<String> iter = dataNode.fieldNames();
            while (iter.hasNext()) {
                String key = iter.next(); //get the key of the object node
                if (key == "itemName") {
                    JsonNode dataVal = dataNode.get(key);
                    System.out.println("KEY:"+key+" VALUE:"+dataVal);
                }
            }

This will give output as below:
 KEY:itemName VALUE:"Table"

That's it in this blog. Hope you found it useful.