简体   繁体   中英

Recursive function to convert from JSON to a Map

I have to make a JSON like

[
  {
    title=X,
    folder=true,
    key=1,
    children=[
        {
        folder=true,
        title=X,
        key=2,
        children=[
            {
            folder=true,
            title=Y,
            key=3
            },
            {
            folder=true,
            title=VH,
            key=4
            },
            {
            folder=true,
            title=Tell,
            key=7
            }
        ]

        },
        {
        folder=true,
        title=X8,
        key=5,
        children=[
            {
            folder=true,
            title=Crah,
            key=6
            }
        ]
        }
    ]
  }
]

And I have to save my structure in a HashMap

{1={parentID=NULL, name=Car}, 2={parentID=1, name=X}, 3={parentID=2, name=Y}, 4={parentID=2, name=VH}, 5={parentID=1, name=X8}, 6={parentID=5, name=Crah}, 7={parentID=2, name=Tell}}

this is the code I have as now:

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class projects {

    public HashMap<Integer, HashMap<String, String>> ld = new HashMap<Integer, HashMap<String, String>>();
    public HashMap child = new HashMap();
    ArrayList alfinal = new ArrayList();

    @SuppressWarnings("uncheck")
    public static  void main(String[] args) {
        // TODO Auto-generated method stub
        projects po =new projects();
        String[] arname = {"Car","X","Y","VH","X8","Crah","Tell"};
        String[] arparent = {"NULL","1","2","2","1","5","2"};
        for (int ii = 1; ii < 8; ii++){
            HashMap hm1 = new HashMap();
            hm1.put("name",arname[ii-1]);
            hm1.put("parentID",arparent[ii-1]);
            po.ld.put(ii, hm1);
        }


        int key=1;
        int depth=2;
        Boolean cdepth = true;
        ArrayList tmp = new ArrayList();
        po.getNodeList(key,depth,tmp);
        System.out.println(tmp);

    }


    public  ArrayList getNodeList(int key,int depth,ArrayList all)
    {
        ArrayList out = new ArrayList();
        out=all;
        HashMap childs = new HashMap();
        ArrayList tmp = new ArrayList();
        if(depth>0)
        {
            childs=getchildes(key);
            tmp=(ArrayList) childs.get(Integer.toString(key));
            depth--;
        }

        if(tmp !=null)
        {


            ArrayList cchin = new ArrayList();
            for (int i = 0; i < tmp.size(); i++) {
                Integer ckey=(Integer) tmp.get(i);
                if(depth>0)
                {
                    ArrayList arrt = new ArrayList();
                    arrt=getNodeList( ckey, depth,out);
                    HashMap hmouti = new HashMap<String, String>();
                    hmouti.put("key", ckey);
                    hmouti.put("title", ld.get(ckey).get("name"));
                    hmouti.put("folder", "true");
                    hmouti.put("children",arrt);
                    out.add(hmouti);

                }

                HashMap hmouti = new HashMap<String, String>();
                hmouti.put("key", ckey);
                hmouti.put("title", ld.get(ckey).get("name"));
                hmouti.put("folder", "true");
                cchin.add(hmouti);


            }

            return cchin;

        }


        return out;


    }



    public HashMap getchildes(int id)
    {
        HashMap child = new HashMap();
        Iterator iter = ld.keySet().iterator();
        while(iter.hasNext()) {
            Integer key = (Integer)iter.next();

            String parentID=ld.get(key).get("parentID");
            if(parentID.equals("NULL")){
                continue;
            }
            else
            {
                if(Integer.toString(id).equals(parentID))
                {
                if(child.get(parentID)!= null)
                {
                    ArrayList tmp = new ArrayList();
                    tmp=(ArrayList) child.get(parentID);
                    tmp.add(key);
                    child.put(parentID, tmp);

                }
                else
                {
                    ArrayList tmp = new ArrayList();
                    tmp.add(key);
                    child.put(parentID, tmp);

                }
                }
            }

        }
        return child;

    }



}

I have written a recursive function but it is missing the parent folder with key... I give key 1 to getNodeList and it returns childs of key 1 but it does not include parent itself (ie key 1 ) .

Please help me identify where is the mistake.

Couple of things

  • your example JSON is invalid - see json.org .
  • your code is, imho, quite hard to follow.

Here's how I'd do this with a recursive function:

public static String toJson(Map.Entry<String, Map<String, String>> entry, Map<String, Map<String, String>> map)
{
  StringBuilder json = new StringBuilder();

  json.append("{")
    .append("\"title\":\"").append(entry.getValue().get("title")).append("\", ")
    .append("\"key\":\"").append(entry.getKey()).append("\", ");

  Collection<Map.Entry<String, Map<String, String>>> children = findChildren(entry.getKey(), map);

  if (!children.isEmpty())
  {
    json.append("\"children\": [ ");

    for (Map.Entry<String, Map<String, String>> childEntry : children)
    {
      json.append(toJson(childEntry, map)).append(", ");
    }

    json.replace(json.length() - 2, json.length(), "").append(" ], ");
  }

  json.replace(json.length() - 2, json.length(), "").append(" }");

  return json.toString();
}

Note: there's no checking for circular references.

This code used a method findChildren that simply returns a Collection of the child entries for a given entry:

private static Collection<Map.Entry<String, Map<String, String>>> findChildren(String key,  Map<String,Map<String, String>> map)
{
  List<Map.Entry<String, Map<String, String>>> children = new ArrayList<>();

  for (Map.Entry<String, Map<String, String>> entry : map.entrySet())
  {
    if (key.equals(entry.getValue().get("parentId")))
    {
      children.add(entry);
    }
  }

  return children;
}

And can be invoked as follows:

Map<String, Map<String, String>> map = new HashMap<>();
map.put("1", createEntity(null, "car"));
map.put("2", createEntity("1", "X"));
map.put("3", createEntity("2", "Y"));
map.put("4", createEntity("2", "VH"));
map.put("5", createEntity("1", "X8"));
map.put("6", createEntity("5", "Crah"));
map.put("7", createEntity("2", "Tell"));

System.out.println(toJson(findEntry(map, "1"), map));

Where the method findEntry returns the entry from the map for the given key, "1" in this case.

This will print (indentation added for readability):

{
  "title":"car",
  "key":"1", 
  "children": [ 
    {
      "title":"X", 
      "key":"2", 
      "children": [ 
        {
          "title":"Y", 
          "key":"3" 
        }, 
        {
          "title":"VH", 
          "key":"4" 
        }, 
        {
          "title":"Tell", 
          "key":"7" 
        } 
      ] 
    }, 
    {
      "title":"X8", 
      "key":"5", 
      "children": [ 
        { 
          "title":"Crah", 
          "key":"6" 
        } 
      ] 
    } 
  ] 
}

please see if modifying the class as below helps you to get desired output

public class projects  {

    public HashMap<Integer, HashMap<String, String>> ld = new HashMap<Integer, HashMap<String, String>>();
    public HashMap child = new HashMap();
    ArrayList alfinal = new ArrayList();

    @SuppressWarnings("uncheck")
    public static  void main(String[] args) {
        // TODO Auto-generated method stub
        projects  po =new projects ();
        String[] arname = {"Car","X","Y","VH","X8","Crah","Tell"};
        String[] arparent = {"NULL","1","2","2","1","5","2"};
        for (int ii = 1; ii < 8; ii++){
            HashMap hm1 = new HashMap();
            hm1.put("name",arname[ii-1]);
            hm1.put("parentID",arparent[ii-1]);
            po.ld.put(ii, hm1);
        }


        int key=1;
        int depth=2;
        Boolean cdepth = true;
        ArrayList tmp = new ArrayList();
        po.getNodeList(key,depth,tmp);
        System.out.println(tmp);

    }


    public  ArrayList getNodeList(int key,int depth,ArrayList all)
    {
        ArrayList out = new ArrayList();
        out=all;
        HashMap childs = new HashMap();
        ArrayList tmp = new ArrayList();
        if(depth>0)
        {
            childs=getchildes(key);
            tmp=(ArrayList) childs.get(Integer.toString(key));
            depth--;
        }
        System.out.println(" tmp  "+tmp);
        if(tmp !=null)
        {


            ArrayList cchin = new ArrayList();
            for (int i = 0; i < tmp.size(); i++) {
                Integer ckey=(Integer) tmp.get(i);

                if(depth>0)
                {
                    ArrayList arrt = new ArrayList();
                    arrt=getNodeList( ckey, depth,out);
                    HashMap hmouti = new HashMap<String, String>();
                    hmouti.put("key", ckey);
                    hmouti.put("title", ld.get(ckey).get("name"));
                    hmouti.put("folder", "true");
                    hmouti.put("children",arrt);
                    out.add(hmouti);

                }

                HashMap hmouti = new HashMap<String, String>();
                hmouti.put("key", ckey);
                hmouti.put("title", ld.get(ckey).get("name"));
                hmouti.put("folder", "true");
                cchin.add(hmouti);


            }

            return cchin;

        }


        return out;


    }



    public HashMap getchildes(int id)
    {
        HashMap child = new HashMap();
        Iterator iter = ld.keySet().iterator();
        while(iter.hasNext()) {
            Integer key = (Integer)iter.next();

            String parentID=ld.get(key).get("parentID");
            if(parentID.equals("NULL")){
                if(id==1)
                {

                    ArrayList tmp = new ArrayList();
                    tmp.add(key);
                    child.put(Integer.toString(id), tmp);

                } 

            }
            else
            { 
                if(Integer.toString(id).equals(parentID))
                {
                    if(child.get(parentID)!= null)
                    {
                        ArrayList tmp = new ArrayList();
                        tmp=(ArrayList) child.get(parentID);
                        tmp.add(key);
                        child.put(parentID, tmp);

                    }
                    else
                    {
                        ArrayList tmp = new ArrayList();
                        tmp.add(key);
                        child.put(parentID, tmp);

                    }
                }
            }

        }
        return child;

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM