I have a problem deserializing a javascript array to c# List class, have read other answers on SO but did not solve my issue.
The Array of Objects
"{\"Id\":\"87\",\"Name\":\"Product x\",\"Cost\":200000,\"Tag\":\"Product_x\"},
{\"Id\":\"88\",\"Name\":\"Product y\",\"Cost\":100000,\"Tag\":\"Product_y\"}"
The products are posted as FormData, so i receive them in the format above.
Product Model
public class Product {
public int Id {get; set;}
public String Name {get; set;}
public decimal Cost {get; set;}
public string Tag {get; set;}
}
And i have a ViewModel
public class ProductViewModel {
[JsonProperty("SerializedProducts")]
public string SerializedProducts{ get; set; } // So this model returns the array of objects above
// Deserializes the SerializedProduct and converts to List of Products.
public List<Product> Products
{
get { return JsonConvert.DeserializeObject<List<Product>>(SerializedProducts); }
set { }
}
}
Error Message Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List `1[Product]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
What i observed I expect SerializedProducts to return an array of object like this
"[{\"Id\":\"87\",\"Name\":\"Product x\",\"Cost\":200000,\"Tag\":\"Product_x\"},
{\"Id\":\"88\",\"Name\":\"Product y\",\"Cost\":100000,\"Tag\":\"Product_y\"}]"
Please i need help. Thank you!
Update
Javascript post
function extractAndFormatFormData(formId) {
var formData = new FormData();
var products = [];
var product = new Product(Id, Name, Cost, Tag);
// Add product to array
products.push(JSON.stringify(product));
// Add products to form
formData.append('SerializedProducts', products);
// I'm also attaching a txt file. This is not an issue at the moment
formData.append('UploadedForm', uploadedFile);
return formData;
}
Ajax post
var formatedFormData = extractAndFormatFormData(formId);
var url = '/Dashboard/provision/';
$.ajax({
url: url,
data: formatedFormData,
type: 'POST',
datatype: 'json',
contentType: false,
processData: false,
cache: false,
success: function (data) {
$('#planDetails').append(data);
},
error: function (err) {
console.log(err);
}
});
[...](which you have in the example at the end). So if you're really receiving it without, add the square brackets.