{
"itemlist":{
"appid":"ST_UWL",
"transid":"STAT_ID_7001",
"overalltransstatus":"O",
"translastmodifieddate":"04.FEB.2016 00:00:00",
"requestor":{
"no":"296111",
"name":"Sowmya Rao",
"adid":"SO29"
},
"workflow":[
{
"no":"296",
"name":"Sowmya Rao",
"adid":"SO296",
"level":"",
"leveltext":"Employee"
},
{
"no":"813",
"name":"Swaroop",
"adid":"SSIV",
"level":"2",
"leveltext":"Supervisor"
}
],
}
}
我有一个上面格式的Json字符串。我必须创建一个控制台应用程序,我必须用新单词和其他新增内容替换字符串中的某些关键字。我试图反序列化,但更不能从数组中选择关键字。它给出了错误
"无法将带有[]的索引应用于类型为' System.Array'的表达式。用C#"。
答案 0 :(得分:0)
尝试使用JsonConvert而不是JavaScriptSerializer反序列化。您需要添加Newtonsoft.Json nuget包并引用它。以下代码将您的字符串反序列化为动态对象,使用该对象可以访问项目的所有属性:
dynamic json = JsonConvert.DeserializeObject<dynamic>(str);
var firstWorkflow = json.itemlist.workflow[0]);
答案 1 :(得分:0)
要获取工作流程,您必须将项目列表转换为Dictionary<string,object
类型,然后再次为您的密钥编制该项目的索引,在本例中为workflow
public void ParseJson()
{
string json =
"{\r\n \"itemlist\":{\r\n \"appid\":\"ST_UWL\",\r\n \"transid\":\"STAT_ID_7001\",\r\n \"overalltransstatus\":\"O\",\r\n \"translastmodifieddate\":\"04.FEB.2016 00:00:00\",\r\n \"requestor\":{\r\n \"no\":\"296111\",\r\n \"name\":\"Sowmya Rao\",\r\n \"adid\":\"SO29\"\r\n },\r\n \"workflow\":[\r\n {\r\n \"no\":\"296\",\r\n \"name\":\"Sowmya Rao\",\r\n \"adid\":\"SO296\",\r\n \"level\":\"\",\r\n \"leveltext\":\"Employee\"\r\n },\r\n {\r\n \"no\":\"813\",\r\n \"name\":\"Swaroop\",\r\n \"adid\":\"SSIV\",\r\n \"level\":\"2\",\r\n \"leveltext\":\"Supervisor\"\r\n }\r\n ]\r\n\r\n }\r\n}";
Dictionary<string, object> dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
object postalCode = ((Dictionary<string, object>)dict["itemlist"])["workflow"];
//Perform operation on postalCode
}