繁体   English   中英

如何从SQL父子关系表中形成嵌套的JSON

[英]How to form nested json from sql parent child relation table

我的SQL过程给出以下输出。 在此处输入图片说明

如果您查看表ID 1,2,5和6有孩子0r 2,3,6,7有父母。 在parentid列中给出了相应的父ID。

现在在C#.Net中,我必须将此表转换为嵌套的json。 这是父元素内的子元素,如下所示。

在此处输入图片说明

怎么做。 请帮忙谢谢

您可以只创建一个具有与表中属性相对应的属性的对象,然后将其序列化为JSON。

如果我不得不刺探那些类是什么,大概是这样的:

public class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string Value {get; set;}
    public PersonAttributes attributes {get; set;}
    public List<Person> Children {get; set;}
}

public class PersonAttributes
{
    public bool HasChild {get; set;}
    public bool HasParent {get; set;}
    public int ParentId {get; set;}
}

然后,您可以对构造函数进行编码,以使用DataTable进行整理并根据需要分配数据。

对于序列化,我建议使用JSON.net ,我一直都在使用它,并且它从未失败过。

这至少应该可以帮助您入门,但是您将需要SQL Server2012。您没有指定使用的版本。

declare @t table (id int, name varchar(50), value varchar(50), HasParent varchar(3), ParentID int, HasChild varchar(3))
insert into @t
exec dbo.YourStoredProc

select
      id
    , name
    , value
    , HasChild 'attributes.HasChild'
    , HasParent 'attributes.HasParent'
    , ParentID  'attributes.ParentId'
    , child.id  'children.id'
    , child.name 'children.name'
    , child.value 'children.value'
    , child.haschild 'children.attributes.haschild'
    , child.hasparent 'children.attributes.hasparent'
    , child.parentid 'children.attributes.parentid'
    , gchild.id 'children.children.id'
    , gchild.name 'children.children.name'
    , gchild.value 'children.children.value'
    , gchild.haschild 'children.children.attributes.haschild'
    , gchild.hasparent 'children.children.attributes.hasparent'
    , gchild.parentid 'children.children.attributes.parentid'
from @t t
join @t child on child.ParentID = t.id
join @t gchild on gchild.ParentID = child.id
for json auto

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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