4th*_*ace 2 .net c# string dictionary split
我有以下字符串:
{"key1":"value1","key2":"value2,some other part of value2"}
Run Code Online (Sandbox Code Playgroud)
我可以使用以下长语法来分割它:
var s = someString.Split(new[] {"\",\""}, StringSplitOptions.RemoveEmptyEntries);
var firstEntryValue = s[0].Split(':')[1];
var secondEntryValue = s[1].Split(':')[1];
Run Code Online (Sandbox Code Playgroud)
由于这个字符串基本上是一个Dictionary<string,string>,我怎样才能将整个事物基本上拉成一行?
我见过这样的话:
var s = someString.Split(new[] {"\",\""}, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split(':'))
.ToDictionary(split => split[0], split => split[1]);
Run Code Online (Sandbox Code Playgroud)
但它抛出并索引越界错误.是否有一些类似的语法可行?
由于字符串遵循JSON格式,因此拆分它不是一个好选择 - 正是因为您提到的问题.
你可以JsonConvert改用:
var res = JsonConvert.DeserializeObject<Dictionary<string,string>>(inputString);
Run Code Online (Sandbox Code Playgroud)