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

本文关键字:我可以 循环 反序列化 JSON 字符串 | 更新日期: 2023-09-27 18:34:09

所以我通过来自 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);
    [...]
}

这是我的请求特权类:

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

我需要能够遍历 JSON 元素,以便我可以进行一些处理,但我还没有能够做到这一点。

谢谢!

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

我认为这可以解决问题。

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,而不是 json 字符串中的单个对象。

试试这个:-

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);
}
您需要像

这样反序列化RequestPrivilege数组:

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

然后,您将能够对其进行foreach

相关文章: