将JSON传递给服务器并将其反序列化为ASP.NET

时间:2015-07-22 07:18:32

标签: c# json

我将JSON代码从JavaScript传递给C#。当我得到JSON服务器端时,我尝试反序列化它,我得到异常“值不能为空。 参数名称:类型“。我使用的JSON是:

{
  "0": {
    "__type": "MyProject.ResultGroupItem",
    "Initiative": {
      "Id": 1,
      "Code": "ABC",
      "Summary": "",
      "Description": "",
    }
  },
  "1": {
    "__type": "MyProject.ResultGroupItem",
    "Initiative": {
      "Id": 2,
      "Code": "XYZ",
      "Summary": "",
      "Description": "",
    }
  }
}

ResultGroupItem类:

public class ResultGroupItem
{
    public Initiative Initiative { get; set; }
}

倡议类:

public class Initiative
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Summary { get; set; }
    public string Description { get; set; }
}

然后当我获得JSON时服务器端,我使用:

List<ResultGroupItem> obj = new JavaScriptSerializer().Deserialize<List<ResultGroupItem>>(jsonString); // Exception: Value cannot be null.

参数名称:type

I tried to move out the List<ResultGroupItem> to a new class, like:

public class Damn
{
    public List<ResultGroupItem> ResultGroupItems { get; set; }
}

And then: 

Damn obj = new JavaScriptSerializer().Deserialize<Damn>(jsonString);  // SAME EXCEPTION

我甚至尝试过使用Newtonsoft.Json库:

Damn obj = JsonConvert.DeserializeObject<Damn>(jsonString); // ResultGroupItems list inside Damn class is null

List<ResultGroupItem> obj = JsonConvert.DeserializeObject<List<ResultGroupItem>>(jsonString);
/* Exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyProject.ResultGroupItem]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
*/

你能告诉我在这种情况下该怎么做,因为我不知道该怎么办?我已经读过JSON中的这个“__type”成员可能会遇到问题,但我也读过Newtonsoft.Json库可以完美地处理它。感谢您提供的任何帮助!

0 个答案:

没有答案