【问题标题】:Recursive function to convert from JSON to a Map从 JSON 转换为 Map 的递归函数
【发布时间】:2014-05-24 02:19:40
【问题描述】:

我必须像 JSON 一样

[
  {
    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
            }
        ]
        }
    ]
  }
]

我必须将我的结构保存在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}}

这是我现在拥有的代码:

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;

    }



}

我编写了一个递归函数,但它缺少带有键的父文件夹...我将键 1 提供给 getNodeList 并返回键 1 的子项,但它不包括父项本身(即键 1 )。

请帮我找出错误在哪里。

【问题讨论】:

  • 不,先生,我不必使用任何库。这是一个要求..我必须递归地做到这一点
  • 是的,我刚刚看到您的字典不是 JSON 字典,而是您自己想要转换为 JSON 的结构。抱歉,没有详细阅读问题。
  • 这是家庭作业 - 仅,不使用 Json 库,并且要求递归执行它听起来可能是这样吗?

标签: java json recursion map


【解决方案1】:

几件事

  • 您的 JSON 示例无效 - 请参阅 json.org
  • 恕我直言,您的代码很难理解。

下面是我如何使用递归函数来做到这一点:

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();
}

注意:不检查循环引用。

这段代码使用了findChildren 方法,它只返回给定条目的子条目Collection

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;
}

并且可以如下调用:

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));

findEntry 方法从map 返回给定键的条目,在本例中为"1"

这将打印出来(为了可读性添加了缩进):

{
  "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" 
        } 
      ] 
    } 
  ] 
}

【讨论】:

    【解决方案2】:

    请查看如下修改类是否有助于获得所需的输出

    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;
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      相关资源
      最近更新 更多