Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a JSON string so I can loop it in C#?

so I am receiving a serialized JSON string through a POST request from a JQuery call:

$('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();
});

The JSON sent looks like this:

{[
  {
    "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"
  }
]}

This is the C# method that handles that call:

[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);
    [...]
}

This is my RequestPrivilege class:

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

I need to be able of loop through the JSON elements so I can do some processing but I haven't been able to do that yet.

Thanks!

like image 869
Multitut Avatar asked Dec 05 '25 08:12

Multitut


1 Answers

I think this will do the trick.

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);
    [...]
}

The difference is in the List instead of just RequestPrivilege. Because you have a LIST, not a single object in your json string.

like image 187
Jauch Avatar answered Dec 07 '25 20:12

Jauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!