Search code examples
javajsonjacksonpojo

Mapping this json to java object (pojo)


I have to map a json which would look like this, it's basicly an object, which can contain the same object again as a child, then that one can also contain the same object again. How would i be able to map this to java pojo's?

This is the json:

    {
"group": [
            {
                "name": "Beheerders",
                "desc": "Beheerders",
                "children" : [
                    "group" : [
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                            "children": [
                                "group" : [
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                },
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                }
                        }

            }
        ]
    }

And i have these 4 pojo's:

Group.java

        private String name;
        private String desc;
        private Children children;

//getters & Setters & toString

GroupList.java

 private ArrayList<Group> group;

    public void setGroup(ArrayList<Group> group) {
        this.group = group;
    }

    public ArrayList<Group> getGroup() {
        return this.group;
    }

Children.java

   private ArrayList<ChildrenGroup> group;

    public ArrayList<ChildrenGroup> getGroup() {
        return this.group;
    }

    public void setGroup(ArrayList<ChildrenGroup> group) {
        this.group = group;
    }

childrengroup.java

    private String name;
    private String desc;
    private Children Children;

//Getters & Setters & toString

This is not working for me, i always get this error:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token


Solution

  • Your JSON is not valid and your objects aren't correctly using object vs List. Please validate your example JSON. "children" : [ "group" : [ is invalid.

    Your errors are occurring because it is encountering [ when your java objects are specifying {.

    You can remove Children and ChildrenGroup and just nest GroupList inside Group as well.