NullPointer exception while parsing JSON Map in java

Viewed 672

I'm trying to parse productId, name, and price from my below JSON in the REST API - but I'm getting null pointer exception when I try to get he name - String name = (String) obj.get("name");, may I know what I'm doing wrong here?

Any help would be really appreciated. Thanks!

JSON:

{
    "id": "af0b86eb-046c-4400-8bc4-0e26042b8f53",
    "products": [{
            "productId": "1234",
            "name": "apple",
            "price": "383939"
        }
    ]
}

Controller.java

public ResponseEntity<Object> create(@RequestBody Map<String, Object> obj) {
    Product response = myservice.create(obj);
    return new ResponseEntity<Object>(response, HttpStatus.CREATED);
}

Service.java

public Product create(Map<String, Object> obj) { 
    for (Entry<String, Object> entry : obj.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }       

    Object [] products = (Object[]) obj.get("products");
    HashMap <String, Object> productOne = (HashMap) products[0];
    String productId = (String) productOne.get("name");
    System.out.println("productId: " +productId);

    String name = (String) obj.get("name");
    System.out.println("name: " +name);
}

Output:

Key : products Value : [{productId=1234, name=apple, price=383939}]
3 Answers

By obj.get("name"), you try getting value by key name from a top-level of your json request, while it's a property of a second-level object

In pseudo-code (skipping casting and null-checks) it should look like this: obj.get("products")[0].get("name")

In Service.java you print obj inside for loop. Your print says that key is products and value is an array of objects.

So in following line obj is that top-level object and not contains “name” field.

String name = (String) obj.get("name");
System.out.println("name: " +name);

What if you call obj.get(“products”) and try to cast it into a collection? Then trying to fetch the first index from the collection. It should contain the inner object which contains name key and value.

You should reason exactly as you see the json, by depth(or level).

Initially the whole json is contained in the obj map which contains two key-value pairs:

(key = "id", value = "af0b86eb-046c-4400-8bc4-0e26042b8f53")
(key = "products", value = [{"productId": "1234", "name": "apple", "price": "383939"}])

Since you are interested in product details, the first step is two extract the array products like this:

Object [] products = obj.get("products");

Now product is an array of objects. Since you know that your objects are in turn hash maps you can cast each object to a map and access the key(s) that you want:

HashMap <String, Object> productOne = (HashMap) products[0];
String productId = (String) productOne.get("productId");
String name = (String) productOne.get("name");
..
Related