3

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}]
2
  • It seems you're getting NPE on the obj instance, make sure it's correctly wired into your service Commented Jan 7, 2019 at 19:49
  • its wired properly, i'm able to print the obj value Commented Jan 7, 2019 at 19:53

3 Answers 3

5

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")

Sign up to request clarification or add additional context in comments.

2 Comments

oh..How to get second-level object :(
I tried this approach obj.get("products")[0].get("name") but Java is not liking this kind of syntax
2

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.

6 Comments

I tried this - Map<String, Object> testobj = (Map<String, Object>) obj.get("products"); System.out.println("value is: " +testobj.get("name")); but I'm getting this exception Caused by: java.lang.ClassCastException: java.util.ArrayList incompatible with java.util.Map
Check @NiVeR answer below.
I tried but getting same kind of exception - not sure why its not working
Hard to reproduce the problem myself but look that exception. Looks like object cannot just cast to Map because obj.get("products") seems to return List type.
So you should cast it into List or ArrayList. Are you using some web framework like Spring here?
|
1

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");
..

1 Comment

I tried this but getting this exception Caused by: java.lang.ClassCastException: java.util.ArrayList incompatible with [Ljava.lang.Object; Update the code in original post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.