How do I deserialize a JSON string so that I can loop over it in C #?
so I am getting serialized JSON string via POST request from 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 transmission 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 this 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 to loop through the JSON elements, so I can do some processing, but I haven't been able to do that yet.
Thank!
+3
source to share
3 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 only difference is in the list instead of RequestPrivilege. Since you have a LIST and not one object in your json string.
+4
source to share
Try this: -
RequestPrivilegeList result = new System.Web.Script.Serialization
.JavaScriptSerializer()
.Deserialize<RequestPrivilegeList>(json);
I have used the following types here: -
public class RequestPrivilegeList
{
public List<RequestPrivilege> data { get; set; }
}
public class RequestPrivilege
{
public string Fachr { get; set; }
public string PrivId { get; set; }
}
Tested with JSON sample: -
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);
}
+1
source to share