将数组格式的字符串转换为C#数组

时间:2019-05-03 23:18:47

标签: c#

我有一个数组格式的字符串,我想转换为实际的数组。

'[[1,"MISSING"],[2,"MISSING"],[6,"MISSING"]]'

是否可以将其转换为数组?

1 个答案:

答案 0 :(得分:2)

好吧,第一件事... C#字符串使用双引号,但是可以忽略,我假设这来自JavaScript,而您想在c#中处理它是正确的吗?

var source= "[[1,\"MISSING\"],[2,\"MISSING\"],[6,\"MISSING\"]]";
// doing it by hand. you could clearly do this more consisely but verbose like this makes it easy to follow i think 
var arrayWithNoExternalCode = new string[10];
var arrayItems = source.Replace("[[","").Replace("]]","").Split(new[] { "],["},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayItems)
{
var parts = item.Split(new[] { ",\""},StringSplitOptions.RemoveEmptyEntries);
var index = parts[0];
var indexValue = parts[1].Replace("\"", "");
Console.WriteLine($"array index: {index}='{indexValue}'");
arrayWithNoExternalCode[Convert.ToInt32(index)] = indexValue;
}
// add using ServiceStack.Text
// via nuget: Install-Package ServiceStack.Text -Version 5.5.0
var easyArray = source.FromJson<string[][]>();