0

This is a result I get from a hashmap in java. How do we read this and extract value1 and value2 and put them inside another hash map? And only one array of object inside.

{
    "result": [
        {
            "desc": {
                "value1": "",
                "value2 ""
            }
        }
    ]
}

This is the method tried,

HashMap result = (HashMap) response.get("result");
HashMap desc = (HashMap) result.get("desc");
map.put("value1", desc.get("value1"));
map.put("value2", desc.get("value2"));
6
  • 2
    response.get("result") isn't a Map, it's a List Commented Dec 23, 2022 at 16:31
  • @azro , do u konw how to achive this? I need to get value1 and value2 from this. There is only one array of object inside. Commented Dec 23, 2022 at 16:36
  • Achieve what ? We don't know the initial class of response. Cas it into a List instead of a Map, and use it like a list Commented Dec 23, 2022 at 16:51
  • @azro this is the type of response -----> HashMap<String, Object> response Commented Dec 23, 2022 at 16:55
  • And what about casting it to list and use like a list then ? Commented Dec 23, 2022 at 16:56

1 Answer 1

1

You're missing the List level

List<Object> result = (List<Object>) response.get("result");
HashMap<String,Object> item = (HashMap<String,Object>) result.get(0);
HashMap<String,String> desc = (<String,String>) item.get("desc");
map.put("value1", desc.get("value1"));
map.put("value2", desc.get("value2"));
Sign up to request clarification or add additional context in comments.

2 Comments

Just to understand, response.get("result").get(0).get("serial").get("id") @azro is this wrong?
@Nickjonas Does it raise an error ? If you don't cast, you have Object and you can't call the get methods

Your Answer

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