在java中把数据库中的Tree Structure转换为JSON对象?

问题描述 投票:1回答:1

我在数据库中有一个父子关系(Tree Structure),我想遍历它并创建一个json对象。

我的数据库中的父子关系结构(演示数据)。

child_id  parent_id   Item_Name
1         1           Country
2         1           Australia
3         2           Victoria
4         2           Queensland
5         1           Canada
6         5           British Columbia
7         6           Vancouver
8         8           Songs
9         8           Song1
10        8           Song2
11        10          lyrics 1st
12        10          lyrics 2nd
13        13          Germany
14        14          England
15        14          London

如何工作

if(child_id == parent_id)
{
   // This item is parent. Like Country,Songs,Germany, England
} else {
  // This item is child. Like Australia, Song1, Vancouver etc.
}

现在,我知道如何遍历这样的结构,但在将其转换为json对象时遇到了麻烦。

伪代码 DFS树

获取所有父母的

List data = fetch data from table where parent_id=child_id

现在穿越这个 资料

Recursively iterate through child elements

get child_id from data object and query on database it as parent_id, to get its child elements and so on.

但是,如何将其转换为JSON对象,比如说

    {
      "country": [
        {
          "Australia": [
            "Victoria",
            "Queensland"
          ]
        },
        {
          "Canada": [
            {
              "British Columbia": [
                "Vancouver"
              ]
            }
          ]
        }
      ]
    },
{
      "Songs": [
        "Songs1",
        {
          "Songs2": [
            "lyrics 1st",
            "lyrics 2nd"
          ]
        }
      ]
    },
{
      "Germany": null
    },
    {
      "England": ["London"]
    }

或一个json对象,其中 亲子关系.

java json recursion tree tree-traversal
1个回答
1
投票

首先,你提供的JSON不是一个有效的JSON。所以,我在生成JSON时添加了一个父根节点。

如果你在你的数据集中定义了一个根节点,那么你的结构会有小的变化,因为你不能像当前的数据集一样保持parent_Id = child_id的关系,所以也会对解决方案进行修改。

首先你需要将你的数据映射到一些父子支持的数据类型中。我已经创建了 Node.java 为此目的。介绍了 addChild 方法来逐个添加子代。

import java.util.ArrayList;
import java.util.List;

public class Node
{
    private String nodeName;
    private java.util.List<Node> children = new ArrayList<Node>();

    public Node( String nodeName )
    {
        this.nodeName = nodeName;
    }

    public List<Node> getChildren()
    {
        return children;
    }

    public void setChildren( List<Node> children )
    {
        this.children = children;
    }

    public String getNodeName()
    {
        return nodeName;
    }

    public void setNodeName( String nodeName )
    {
        this.nodeName = nodeName;
    }

    public void addChild( Node node )
    {
        this.children.add( node );
    }
}

而对于你最初的数据类型,我创建了 Mapping.java

public class Mapping
{
    private int parentId;
    private int childId;
    private String ItemName;

    public Mapping( int parentId, int childId, String itemName )
    {
        this.parentId = parentId;
        this.childId = childId;
        ItemName = itemName;
    }

    public int getParentId()
    {
        return parentId;
    }

    public void setParentId( int parentId )
    {
        this.parentId = parentId;
    }

    public int getChildId()
    {
        return childId;
    }

    public void setChildId( int childId )
    {
        this.childId = childId;
    }

    public String getItemName()
    {
        return ItemName;
    }

    public void setItemName( String itemName )
    {
        ItemName = itemName;
    }
}

现在加载和数据并填充Node对象,得到最终的Json就在这里完成。我这里使用的是对象引用映射,因为我们无法保证你数据库中映射的顺序。因为子代是分配给父代的对象引用的,完成分配后,我们就有了父子结构。这两个循环也是出于同样的原因。在开始构建结构之前,我们需要确保map拥有所有节点。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParentChild
{
    public static void main( String[] args )
    {
        List<Mapping> list = new ArrayList<Mapping>();
        list.add( new Mapping( 1, 1, "Country" ) );
        list.add( new Mapping( 1, 2, "Australia" ) );
        list.add( new Mapping( 2, 3, "Victoria" ) );
        list.add( new Mapping( 2, 4, "Queensland" ) );
        list.add( new Mapping( 1, 5, "Canada" ) );
        list.add( new Mapping( 5, 6, "British Columbia" ) );
        list.add( new Mapping( 6, 7, "Vancouver" ) );
        list.add( new Mapping( 8, 8, "Songs" ) );
        list.add( new Mapping( 8, 9, "Song1" ) );
        list.add( new Mapping( 8, 10, "Song2" ) );
        list.add( new Mapping( 10, 11, "lyrics 1st" ) );
        list.add( new Mapping( 10, 12, "lyrics 2nd" ) );
        list.add( new Mapping( 13, 13, "Germany" ) );
        list.add( new Mapping( 14, 14, "England" ) );
        list.add( new Mapping( 14, 15, "London" ) );

        Map<Integer, Node> map = new HashMap<Integer, Node>();

        map.put( -1, new Node( "root" ) ); // give index -1 for the root

        for( Mapping mapping : list )  // keep a map of nodes by child id
        {
            map.put( mapping.getChildId(), new Node( mapping.getItemName() ) );
        }

        for( Mapping mapping : list )
        {
            if( mapping.getParentId() == mapping.getChildId() )
            {
                map.get( -1 ).addChild( map.get( mapping.getChildId() ) ); // add to the root
            }
            else
            {
                Node node = map.get( mapping.getParentId() );
                Node childNode = map.get( mapping.getChildId() );
                node.addChild( childNode ); // add to the relevant parent
            }
        }

        StringBuilder json = new StringBuilder();
        writeJson( map.get( -1 ), json ); // root node is enough
        System.out.println( json );
    }

    private static void writeJson( Node node, StringBuilder json )
    {
        if( node.getChildren().isEmpty() ) // no children. return just the node name
        {
            json.append( "\"" ).append( node.getNodeName() ).append( "\"" );
        }
        else
        {
            json.append( "{\"" ).append( node.getNodeName() ).append( "\": [" );

            List<Node> children = node.getChildren();
            for( int i = 0; i < children.size(); i++ )
            {
                Node child = children.get( i );
                writeJson( child, json ); // call recursively
                if( i != children.size() - 1 ) // skip , for the last child
                {
                    json.append( "," );
                }
            }
            json.append( "]}" );
        }
    }
}

我使用了一个递归的方法来构建json。

最终的json

{
   "root":[
      {
         "Country":[
            {
               "Australia":[
                  "Victoria",
                  "Queensland"
               ]
            },
            {
               "Canada":[
                  {
                     "British Columbia":[
                        "Vancouver"
                     ]
                  }
               ]
            }
         ]
      },
      {
         "Songs":[
            "Song1",
            {
               "Song2":[
                  "lyrics 1st",
                  "lyrics 2nd"
               ]
            }
         ]
      },
      "Germany",
      {
         "England":[
            "London"
         ]
      }
   ]
}

希望对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.