如何反序列化JSON字符串,以便我可以在C#中循环它?

时间:2014-12-14 17:10:11

标签: c# json serialization

所以我通过来自JQuery调用的POST请求收到序列化的JSON字符串:

$('input:checkbox:checked.solPrivChck').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
    requestedApprobal.push({ 'PrivId': $(this).attr('id'), 'Fachr': $(this).attr('fachr') });
});
$.post("/Home/RequestPrivilege", { allRequests: JSON.stringify(requestedApprobal) }).success(function () {
    loadTable();
});

发送的JSON看起来像这样:

{[
  {
    "PrivId": "00005",
    "Fachr": "0039"
  },
  {
    "PrivId": "00006",
    "Fachr": "0039"
  },
  {
    "PrivId": "00007",
    "Fachr": "0039"
  },
  {
    "PrivId": "00010",
    "Fachr": "0039"
  },
  {
    "PrivId": "00005",
    "Fachr": "0039"
  },
  {
    "PrivId": "00006",
    "Fachr": "0039"
  },
  {
    "PrivId": "00007",
    "Fachr": "0039"
  },
  {
    "PrivId": "00010",
    "Fachr": "0039"
  }
]}

这是处理该调用的C#方法:

[HttpPost]
public string RequestPrivilege(string allRequests)
{  
    [...]
    //I am trying to map it to a class with the same structure but it fails
    RequestPrivilege allRequestsObj = JsonConvert.DeserializeObject<RequestPrivilege>(allRequests);
    [...]
}

这是我的RequestPrivilege类:

class RequestPrivilege {
    public string Fachr { get; set; }
    public string PrivId { get; set; }
}

我需要能够遍历JSON元素,这样我才能进行一些处理,但我还没能做到。

谢谢!

3 个答案:

答案 0 :(得分:4)

我认为这样可以解决问题。

public class RequestPrivilege
{
    [JsonProperty("Fachr")]
    public string Fachr { get; set; }

    [JsonProperty("PrivId")]
    public string PrivId { get; set; }
}

[HttpPost]
public string RequestPrivilege(string allRequests)
{  
    [...]
    List<RequestPrivilege> allRequestsObj = JsonConvert.DeserializeObject<List<RequestPrivilege>>(allRequests);
    [...]
}

区别在于List而不仅仅是RequestPrivilege。 因为你有一个LIST,而不是你的json字符串中的单个对象。

答案 1 :(得分:1)

试试这个: -

RequestPrivilegeList result = new System.Web.Script.Serialization
                                        .JavaScriptSerializer()
                                        .Deserialize<RequestPrivilegeList>(json);

在这里,我使用了这些类型: -

public class RequestPrivilegeList
{
   public List<RequestPrivilege> data { get; set; }
}

public class RequestPrivilege
{
   public string Fachr { get; set; }
   public string PrivId { get; set; }
}

使用示例JSON测试: -

string json =  @"{""data"":[{""PrivId"": ""00005"", ""Fachr"": ""0039"" },
                 {""PrivId"": ""00006"", ""Fachr"": ""0039"" }]}";

foreach (var item in result.data)
{
    Console.WriteLine("PrivId: {0},Fachr: {1}", item.PrivId, item.Fachr);
}

答案 2 :(得分:0)

您需要反序列化RequestPrivilege数组,如下所示:

JsonConvert.DeserializeObject<RequestPrivilege[]>(allRequests);

然后,您就可以foreach覆盖它。