I'm bulding an array of object in javascript as follows :
var tabDiscount = []
for(var i=0; i<someArray.length; i++){
var refdiscountpair = { productCode: $("#Ref" + i).html(), discount: discountValue }
tabDiscount.push(refdiscountpair);
}
which seems to work fine. I then store this array in an hiddefield
$HFDiscount.val(JSON.stringify(tabDiscount));
so when the form is posted I get the hiddenfield value server-side. I have a C# class RefDiscountPair :
[Serializable]
public class RefDiscountPair
{
public string productCode
{
get;
set;
}
public int discount
{
get;
set;
}
public RefDiscountPair()
{
}
}
and I try to deserialize the array of javascript object into an array of RefDiscountPair. I've tried using the JSON .NET package (Newtonsoft.Json) :
RefDiscountPair[] test = JsonConvert.DeserializeObject<RefDiscountPair[]>(HFDiscount.Value);
whcih raises a JsonSerializationException.
I've also tried to use the JavaScriptSerializer class :
string[] test = js.Deserialize<string[]>(js.Deserialize<string>(HFDiscount.Value));
foreach (string s in test)
{
RefDiscountPair p = js.Deserialize<RefDiscountPair>(s);
}
Exception
MissingMethodException(no parameterless constructor defined for type of 'system.string'. javascriptserializer).
Any ideas ?
EDIT
This is the structure of the JSON I recieve :
"\"[{\\\"productCode\\\": \\\"1111111\\\", \\\"discount\\\": \\\"5\\\"}, {\\\"productCode\\\": \\\"2222222\\\", \\\"discount\\\": \\\"5\\\"}]\""
which result in the following error message :
Error converting value "[{"productCode": "1111111", "discount": "5"}, {"productCode": "2222222", "discount": "5"}]"
stringat the end of your json?