-1

I converted java.lang.String to or.simple.json.JSONObject. Now I'm unable to cast it to HashMap.

org.json.JSONObject jso = new org.json.JSONObject("{"phonetype":"N95","cat":"WP"}");        
LinkedHashMap h = (LinkedHashMap) jso.get("phonetype");
System.out.println(h);

and I'm getting an error:

"java.lang.String cannot be cast to java.util.LinkedHashMap"

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

1
  1. JSONObject has following constructor

    public JSONObject(Map map) { super(map); }

This means you cannot create JSONObject, passing String in consctructor. But you can using map

Map<String, String> map = new LinkedHashMap<>();
    map.put("phonetype","N95");
    map.put("cat", "WP");
    JSONObject jso = new JSONObject(map);
  1. get method has signature

    public V get(Object key)

This means that if you want to get map, value should be Map generic. For example

        Map<String, String> map = new LinkedHashMap<>();
    map.put("phonetype","N95");
    map.put("cat", "WP");

    Map<String, Map> toConstructor = new LinkedHashMap() {{
        put("map", map);
    }};
    JSONObject jso = new JSONObject(toConstructor);
    LinkedHashMap h = (LinkedHashMap) jso.get("map");
    System.out.println(h);

In your case you try to cast String to LinkedHashMap, so ClassCastException was thrown

Oleg Zinoviev
  • 549
  • 3
  • 14