我想将以下表示表单数据的json字符串反序列化为对象。原始对象包含List元素(使用Razor渲染)
{
"Office":"10649273-8412-4ac0-9109-085b04b49964",
"SearchItemList[0].Column":"Account",
"SearchItemList[0].Operation":"0",
"SearchItemList[0].Value":"be5a36a7-c301-44d7-8d40-85e9637b5b14",
"SearchItemList[1].Column":"",
"SearchItemList[1].Operation":"0",
"SearchItemList[1].Value":"",
"SearchItemList[2].Column":"",
"SearchItemList[2].Operation":"0",
"SearchItemList[2].Value":"",
"SearchItemList[3].Column":"",
"SearchItemList[3].Operation":"0",
"SearchItemList[3].Value":"",
"SearchItemList[4].Column":"",
"SearchItemList[4].Operation":"0",
"SearchItemList[4].Value":"",
"SearchItemList[5].Column":"",
"SearchItemList[5].Operation":"0",
"SearchItemList[5].Value":""
}
答案 0 :(得分:0)
您的问题并未指定要反序列化为哪种对象。如果您不太在意,那么简单的方法就是将该JSON反序列化为Dictionary<string, string>
。然后,您可以从中选择所需的任何键-它们将与JSON中的键相同。例如(我在这里使用Json.Net)
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Console.WriteLine(dict["SearchItemList[0].Column"] + ": " + dict["SearchItemList[0].Value"]);
这将输出:
Account: be5a36a7-c301-44d7-8d40-85e9637b5b14
但是,我怀疑您真正想要的是将数据恢复为类似于“原始对象”的某种类结构,我认为它看起来像这样:
class RootObject
{
public string Office { get; set; }
public List<SearchItem> SearchItemList { get; set; }
}
class SearchItem
{
public string Column { get; set; }
public string Operation { get; set; }
public string Value { get; set; }
}
为此,您可以将JSON反序列化为JObject
,然后使用标准的System.Linq
方法从那里将其转换为所需的结果:
JObject obj = JObject.Parse(json);
RootObject root = new RootObject
{
Office = (string)obj["Office"],
SearchItemList =
obj.Properties()
.Where(p => p.Name.StartsWith("SearchItemList["))
.Select(p =>
{
var parts = p.Name.Split(new string[] { "[", "]." }, 3, StringSplitOptions.None);
return new
{
Index = int.Parse(parts[1]),
Property = new JProperty(parts[2], p.Value)
};
})
.GroupBy(a => a.Index)
.OrderBy(g => g.Key)
.Select(g => new JObject(g.Select(a => a.Property)).ToObject<SearchItem>())
.ToList()
};