我是C#的Json新手。我试图反序列化JSON字符串以显示到数据网格中。 我成功从服务器获取JSON字符串,但在尝试反序列化时,它会抛出此异常:
Newtonsoft.Json.JsonSerializationException:转换值时出错 “id”键入'Eng_Tab.JsonData'。路径'[0]',第1行,位置5. ---> System.ArgumentException:无法从System.String转换或转换 到Eng_Tab.JsonData。
这是数据类:
公共类JsonData { public int id {get;组; } public string lec {get;组; } public string sec1 {get;组; } public string sec2 {get;组; } public string sec3 {get;组; } public string sec4 {get;组; } public string sec5 {get;组; } public string sec6 {get;组; } public string sec7 {get;组; } public string sec8 {get;组; } public string sec9 {get;组; } public string sec10 {get;组; }
public int h { get; set; } public int h1 { get; set; } public int h2 { get; set; } public int h3 { get; set; } public int h4 { get; set; } public int h5 { get; set; } public int h7 { get; set; } public int h8 { get; set; } public int h9 { get; set; } public int h10 { get; set; } public int m { get; set; } public int m1 { get; set; } public int m2 { get; set; } public int m3 { get; set; } public int m4 { get; set; } public int m5 { get; set; } public int m6 { get; set; } public int m7 { get; set; } public int m8 { get; set; } public int m9 { get; set; } public int m10 { get; set; } }
这是Json字符串:
[ “ID” 为 “1”, “H”: “7”, “M”: “0”, “LEC”: “”, “H1”: “0”, “M1”: “0” “SEC1”: “”, “H2”: “10”, “M2”: “0”, “秒2”:“Abdelrahman Mohamed401119343000" , “H3”: “10”, “M3”: “0”, “SEC3”:“Abdelrahman Mohamed401119343000" , “H4”: “5”, “M4”: “0”, “SEC4”: “A401119343000”, “H5”: “5”, “M5”: “0”, “sec5”: “A401119343000” “H6”: “5”, “M6”: “0”, “sec6”: “A401119343000”, “H7”: “5”, “M7”: “0”, “sec7”: “A401119343000”,” H8 “:” 5" , “M8”: “0”, “sec8”: “A401119343000”, “H9”: “18”, “M9”: “0”, “sec9”:“Abdelrahman Mohamed401119343000“,”h10“:”0“,”m10“:”0“,”sec10“:”set sec“]
这是我的C#代码:
string qry =“de = e1& id = 1”;
WebRequest request = WebRequest.Create(“php link”+ qry);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.ASCII);
string jsonData = reader.ReadToEnd();
jsonData = jsonData.Replace(“{”,“[”)。Replace(“}”,“]”);
MessageBox.Show(jsonData);
列出
<JsonData>
result = JsonConvert.DeserializeObject<List<JsonData>>
(jsonData);metroGrid1.DataSource = result;
答案 0 :(得分:0)
您需要在Json字符串中使用类型JsonData
的对象进行反序列化。因此,您的JSON字符串应该看起来像[{"ABC":"PQR", ...}]