如何将其转化为更多的东西很好理解 - JSON:
string ConvertToJson(string input)
{
var elements = input
// replace all square brackets with quotes
.Replace("[[", "\"").Replace("]]", "\"")
// fix double quotes
.Replace("\"\"", "\"")
// split on all space-quote combos
.Split(new[] { " \"" }, StringSplitOptions.RemoveEmptyEntries)
// make sure all elements start and end with a quote
.Select(x => "\"" + x.Trim('"') + "\"")
// make all odd elements the parent item and all even the children collection
.Select((x, i) => (i % 2 == 0)
? ("{\"item\":" + x)
: ",\"children\":[" + x + "]},");
// turn back into string, remove unneeded comma at end and wrap in an array
return "[" + String.Concat(elements).Trim(',') + "]";
}
输入:
[[Parent1 [[Child 1]],[[Child 2]],[[Child 3]]]] [[Parent2 [[Child 1]],[[Child 2]]]]
输出:
[{"item":"Parent1","children":["Child 1","Child 2","Child 3"]},{"item":"Parent2","children":["Child 1","Child 2"]}]
然后可以使用JSON.NET或任何玩与你一样。
您还会注意到,此解决方案对父母被称为Parent
没有要求,因为此处提供了其他解决方案。作为奖励,在看不到正则表达式...
为了完整这里使用JSON.NET到反序列化的例子:
var list = JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach (var item in list)
{
Console.WriteLine("item: {0}", item.item);
Console.WriteLine("Children: [{0}]", String.Join(", ", item.children));
}
其输出
项目:父母1
孩子:[孩子1,孩子2,孩子3]
项目:父母2
儿童:[儿童1,儿童2]
您可以像这样得到'[[Child1]],[[Child2]],[[Child3]]'不像'[Child1,Child2, Child3]' – 2014-09-19 10:50:12
是的。那很好。但是如何?谢谢。 – Paul 2014-09-19 10:51:40
你必须用\ – HimBromBeere 2014-09-19 10:56:37