【问题标题】:How to form nested json from sql parent child relation table如何从sql父子关系表中形成嵌套的json
【发布时间】:2015-03-20 11:13:42
【问题描述】:

我的 sql 过程给出以下输出。

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

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

怎么做。请帮忙谢谢

【问题讨论】:

    标签: c# sql-server json


    【解决方案1】:

    这至少可以帮助您入门,但您需要 SQL Server 2012。您没有指定您正在使用的版本。

    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
    

    【讨论】:

    • 谢谢。当我发布这个问题时,我使用的是 sql server 2008 版本。
    【解决方案2】:

    您可以只创建一个具有与表中的属性相对应的属性的对象,然后将其序列化为 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,我一直在使用它,它从来没有让我失望过。

    【讨论】:

    • 嗨,chriszumberge,感谢您的评论。它给了我如何实现它的基本想法。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多