Hierarchical JSON Data to Hierarchical Table

I have a class like this and to this type I need to deserialize a JSON string

public class nodes
{
    public int id{get;set;}
    public string name{get;set;}
    public List<nodes> children{get;set;}
}

and the JSON is like this

{
  id: 15,
  name: 'user1',
  children: [
    {
      id: 22,
      name: 'user2',
      children: [
        {
          id: 34,
          name: 'user3',
          children: [
            {
              id: 43,
              name: 'user4',
              children: []
            },
            {
              id: 54,
              name: 'user5',
              children: []
            }
          ]
        },
        {
          id: 65,
          name: 'user6',
          children: []
        }
      ]
    },
    {
      id: 72,
      name: 'user7',
      children: []
    }
  ]
}

This is how I'm deserialising

node d=JsonConvert.DeserializeObject<node>(myJSON); //myJSON is my above JSON string

But the requirement is I need to insert these data into an SQL table as separate rows. The table should is as follows

UniqueID    id    name    ParentID
------------------------------------
    1       15    User1     0
    2       22    User2     1
    3       34    User3     2
    4       43    User4     3
    5       54    User5     3
    6       65    User6     2
    7       72    User7     1
--------------------------------------

As you see the table there is a system generated ID column UniqueID . Also another column ParentID to keep the hierarchy..

I can ofcourse use some recursive functions to handle each children to their details and create a dynamic query to insert. But I dont think its a best solution. Please suggest a better way to do this


How about flattening your tree via Linq (it is still going to use recursion), I think it may make it clearer. You could then just loop throught the result. I'm thinking something like this:

First write an extension method:

public static IEnumerable<T> Flatten<T>(
    this IEnumerable<T> c,
    Func<T,IEnumerable<T>> f) 
{
    return c.SelectMany(n => f(n).Flatten(f)).Concat(c);
}

Then you can flatten and loop:

var nodesList = nodes.Flatten(node => node.children).ToList();

foreach(var n in nodeList)
{
    /add to db
}
链接地址: http://www.djcxy.com/p/802.html

上一篇: 在一段时间后强制终止方法

下一篇: 分层JSON数据到分层表