c# - 将 JSON 字符串转换为有意义的完整数据进行解析

标签 c# javascript sql regex

好的,我有这个字符串:

[{"id":1},{"id":2,"children":[{"id":3},{"id":4,"children":[{"id":5,"children":[{"id":6}]}]},{"id":7}]}]

我希望能够解析它并将其用作有意义的数据来输入我的数据库。

解析后的输出,作为数组/或者如果您认为从中提取数据更好,您可以建议不同的输出。这只是我的想法。

[0]  id:1
[1]  id:2 -> id:3, id:4 -> id:5 -> id:6
[2]  id:7

使用正则表达式是否可以实现这一点

为了让您更好地理解我为什么问您这个问题。我有一个树结构 在这里:

演示: http://jsbin.com/UXIpAHU/3/edit

我希望能够解析输出并将其保存到 2 列的 SQL 数据库中

ID 列包含所有项目的所有 id,但只有子项或具有父项的 id 才会具有parentID。所以根据 DEMO,sql 表看起来像这样:

ID | ParentID
------------------------
1     NULL
2     NULL
3      2
4      2
5      4
6      5
7      2

实现这一目标的最佳方法是什么,我正在为我的问题寻找一些想法/解决方案。谢谢。

最佳答案

OP更改了问题,因此以下内容基于之前的问题:

如果您控制输出,那么您应该使用 XML 作为传输语言。它使用起来非常简单,并且 C# 对其有内置支持。

你的结果如下:

{"id":1},{"id":2->"children":{"id":3},{"id":4->"children":{"id":5->"children":{"id":6}}},{"id":7}}

会变成:

<root>
    <item id="1" />
    <item id="2">
        <item id="3" />
        <item id="4">
            <item id="5">
                <item id="6" />
            </item>
        </item>
        <item id="7" />
    </item>
</root>

然后您可以使用以下方式阅读:

XElement root = XElement.Parse(xml); // or .Load(file)
Dictionary<int,int?> list = root.Descendants("item")
    .ToDictionary(x => (int)x.Attribute("id"), x => 
    {
        var parentId = x.Parent.Attribute("id");
        if (parentId == null)
            return null;
        return (int)parentId;
    });

现在你有了一个键值对的字典列表,正如你想要的那样

ID | ParentID
------------------------
1     NULL
2     NULL
3      2
4      2
5      4
6      5
7      2

=== 转换回来 ===

Dictionary<int, int?> dic = new Dictionary<int, int?>
{
    {1,null},
    {2,null},
    {3,2},
    {4,2},
    {5,4},
    {6,5},
    {7,2}
};

XElement root = new XElement("root");
foreach (var kvp in dic)
{
    XElement node = new XElement("item", new XAttribute("id", kvp.Key));

    int? parentId = kvp.Value;
    if (null == parentId)
        root.Add(node);
    else
    {
        // Get first item with id of parentId
        XElement parent = root.Descendants("item")
            .FirstOrDefault(i => (int)i.Attribute("id") == (int)parentId);
        if (null != parent) // which it shouldn't for our array
            parent.Add(node);
    }
}

要获取字符串,请使用:

string xml = root.ToString();

或者保存到文件:

root.Save("filepath");

关于c# - 将 JSON 字符串转换为有意义的完整数据进行解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19183838/

相关文章:

sql - 使用选择查询插入

c# - 如何为 .NET Core 控制台应用程序创建独立的可执行文件?

c# - 针对 C++ 和 C# 的代码生成工具

javascript - BootstrapVue 访问 slot 模板中的 b-table 行数据

javascript - 将 JSON 数据转换为 JavaScript 二维数组

sql - 如何处理SQL中的日期转换错误?

c# - 简单注入(inject)器 Web Api Controller 构造函数注入(inject)失败

c# - 生成一个无需C++可再发行组件包即可运行的.exe

javascript - 最小文件和常规文件有什么区别,我应该使用哪一个?

mysql - SQL:如何使用 SQL 查询获取一行中的项目值?