我有一个问题,将一个javascript数组反序列化为c#List类,在SO上读过其他答案,但没有解决我的问题。
对象数组
"{\"Id\":\"87\",\"Name\":\"Product x\",\"Cost\":200000,\"Tag\":\"Product_x\"},
{\"Id\":\"88\",\"Name\":\"Product y\",\"Cost\":100000,\"Tag\":\"Product_y\"}"
产品以FormData的形式发布,所以我会以上面的格式收到它们。
产品型号
public class Product {
public int Id {get; set;}
public String Name {get; set;}
public decimal Cost {get; set;}
public string Tag {get; set;}
}
我有一个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 { }
}
}
错误消息 无法将当前JSON对象(例如{\“name \”:\“value \”})反序列化为类型'System.Collections.Generic.List`1 [Product]',因为该类型需要JSON数组(例如[1, 2,3])正确反序列化。
我观察到的内容 我希望SerializedProducts返回像这样的对象数组
"[{\"Id\":\"87\",\"Name\":\"Product x\",\"Cost\":200000,\"Tag\":\"Product_x\"},
{\"Id\":\"88\",\"Name\":\"Product y\",\"Cost\":100000,\"Tag\":\"Product_y\"}]"
我需要帮助。谢谢!
更新
Javascript帖子
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;
}
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);
}
});
答案 0 :(得分:3)
在Javascript中,在产品数组上使用stringfy,而不是在数组项中使用。
代码:
function extractAndFormatFormData(formId) {
var formData = new FormData();
var products = [];
var product = new Product(Id, Name, Cost, Tag);
// Add product to array
products.push(product);
// Add products to form
formData.append('SerializedProducts', JSON.stringify(products));
// I'm also attaching a txt file. This is not an issue at the moment
formData.append('UploadedForm', uploadedFile);
return formData;
}