Reputation: 487
Lets say I have set up things like this:
narudzbe.aspx.cs
[WebMethod]
public static string getAllPartnere(int kid)
{
string json = string.Empty;
List<stp_WEB_MP_PARTNERI_GetPartneriDDList_Result> partnerList = new List<stp_WEB_MP_PARTNERI_GetPartneriDDList_Result>();
partnerList = DANarudzbe.GetPartnerList(kid);
json = JsonConvert.SerializeObject(partnerList, new Newtonsoft.Json.Converters.StringEnumConverter());
return json;
}
narudzbe.aspx - javascript
$.ajax({
type: "POST",
url: "/Narudzbe/narudzbe.aspx/getAllPartnere",
data: '{kid:"' + Partner_ID + '"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#partneri').DataTable({
data: msg.d,
columns: [
{ title: "PartnerID" },
{ title: "Naziv" }
]
});
}
});
narudzbe.aspx - html
...
<table class="display dataTable" id="partneri"></table>
...
I need to know how to use json.net to serialize generic list so that all values are enclosed in quotation marks so that returned list is serialized so that data tables are able to read it.
Serialized list does not have numerical values in quotation marks when serialized like I did so datatables gets some of " quotation marks recognized as values.
I also need to state that this is the first time that I'm using datatables and am not a developer so take it easy on me.
Well to be honest I want to know also if this is the correct way to use in datatables with ajax and server processing or is there easier and more simplistic way.
Upvotes: 1
Views: 401
Reputation: 595
I don't think you have a problem with your numeric values as they are serialized correctly, as numeric values and that is the default behaviour. You can check that there is no problem with it in this jsfiddle Check first ten rows, there are only integer values, displayed correctly.
However, to answer your question. There is no converter or some other simple way to say json.net how to convert your numeric into string (like there is for date, or enum like from your own example). You would have to write your own converter like it is shown here. But that looks like an overhead.
If your original class is not that big I would create a copy of it with all string properties in it.
public class SerializablePartner
{
public string PartnerId { get; set; }
public string Naziv { get; set; }
// your other properties
public SerializablePartner(stp_WEB_MP_PARTNERI_GetPartneriDDList_Result originalItem)
{
// map your values here
this.PartnerId = originalItem.PartnerId.ToString();
this.Naziv = originalItem.Naziv; // already a string, no need for change
// your other properties
}
}
That way all your properties will be for sure enclosed in double quotes as for json.net they are strings. And of course your original partnerList would have to be converted to List<SerializablePartnerList> prior to doing json conversion. Something like this:
return JsonConvert.SerializeObject(partnerList.Select(partner => new SerializablePartner(partner)).ToList());
Upvotes: 1