1

I have json file

{"q":{"name": "Alex"}}

Class People

private String name;

I try to pars json into LinkedHashMap<String, People>.

    public class Parser {    
        public Root read(){
            LinkedHashMap<String, People> w=new ObjectMapper().readValue("{\"q\":{\"name\":\"Alex\"} }",LinkedHashMap.class);
            Root root=new Root();
            root.setMap(w);
            return root;
        }
    }

  //Class Root has private LinkedHashMap<String, People> map;

I try to cast root.getMap().get("q"). It's working ok, but when I cast root.getMap().get("q").getClass():

Exception in thread "main" java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class Collect.Root (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; Collect.Root is in unnamed module of loader 'app')

I tried to put another object in Linkedhashmap root and compare them in debugging

    People test=new People();
    test.name="qqq";
    Parser pars = new Parser();
    Root root = pars.read();
    root.put("w",test);

enter image description here

As I understand it, the Parser does not understand that there is an object of type People in {...}

    System.out.println(w.get("q")+" | "+w.get("w"));

enter image description here

I do not know how else to simplify the code, because if I remove something else, the error disappears

  • 1
    `parser.read()` returns a `Root` object, but you are assigning it to a variable of type `LinkedHashMap`. The statement `LinkedHashMap root= parser.read();` should not compile, so the code you are showing cannot be the code that's executing. Please elaborate. – Bohemian Dec 22 '21 at 00:57
  • Parser parser = new Parser(); Root root= parser.read(); System.out.println(root.getMap().get("q").getClass()); – Oleg Boldov Dec 22 '21 at 17:56
  • Please indicate exactly which line is throwing the exception. Break up the line into separate steps, eg `LinkedHashMap map = root.getMap(); People p = map.get("q");` etc to discover which operation is throwing the exception. – Bohemian Dec 22 '21 at 20:39
  • I have already found out and said that I catch an exception when I try to work with People objects in map. For example, the line will cause an exception: root.getMap().get("q").toString() or root.getMap().get("q").getClass(). But root.getMap().get("q") works correctly. – Oleg Boldov Dec 23 '21 at 00:18
  • Run your code in a debugger. Inspect the map and its contents. See [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173) – Bohemian Dec 23 '21 at 01:57
  • Edit your question to include an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example) that doesn't involve your file, eg just `String q = "some json string";` and the least code possible so we can run your code to reproduce your error with only the relevant code required. – Bohemian Dec 23 '21 at 02:00

0 Answers0