将 JSON 字符串转换为要解析的完整数据

Convert JSON string into meaning full data to parse

本文关键字:整数 数据 JSON 字符串 转换      更新时间:2023-09-26

好的,所以我有这个字符串:

[{"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 才会具有父项 ID。 因此,根据 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");

您可以将其反序列化为一个类,然后轻松地从中提取数据。

请注意,System.Web.Script.Serialization.JavaScriptSerializer 位于 System.Web.Extensions 中

[Serializable()]
public class Info
{
 private int _id;
 private List<Info> _children;
 public int Id {
  get { return _id; }
  set { _id = value; }
 }
 public List<Info> Children {
  get { return _children; }
  set { _children = value; }
 }
}

public void Main()
{
 string json = null;
 List<Info> result = null;
 System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
 json = "[{'"id'":1},{'"id'":2,'"children'":[{'"id'":3},{'"id'":4,'"children'":[{'"id'":5,'"children'":[{'"id'":6}]}]},{'"id'":7}]}]";
 result = ser.Deserialize<List<Info>>(json);
 foreach (Info p in result) {
  Console.WriteLine(p.Id);
  if (p.Children != null) {
   foreach (Info c in p.Children) {
    Console.WriteLine("   " + c.Id);
   }
  }
 }
 Console.ReadLine();
}

使用 Json.NET,您可以简单地传递字符串即可获得 JObjects 的 JArray:

JArray arr = JArray.Parse(yourString)

然后,可以像在任何支持 LINQ 的集合上使用 LINQ 一样使用 LINQ。