I have this JSON string that I want to convert to a List of objects in C# asp.net.
In VS I can see the json string appears like this:
"{\"orders\":[{\"ItemID\":\"6\",\"Quantity\":\"8\",\"CategoryID\":\"2\",\"Price\":\"0.5\",\"ItemName\":\"Focaccia\",\"ItemDesc\":\"Focaccia is a flat oven-baked Italian bread similar in style and texture to pizza; in some places, it is called pizza bianca. \",\"ItemImg\":\"Images/Focaccia.jpg\",\"InCart\":1}]}"
but in browser local storage, the json is well formatted and appears like this:
{
"orders": [
{
"ItemID": "6",
"Quantity": "8",
"CategoryID": "2",
"Price": "0.5",
"ItemName": "Focaccia",
"ItemDesc": "Focaccia is a flat oven-baked Italian bread similar in style and texture to pizza; in some places, it is called pizza bianca. ",
"ItemImg": "Images/Focaccia.jpg",
"InCart": 1
}
]
}
I want to convert it to a FoodItem objects array list , below is the class code:
public class FoodItem : Item
{
private string quantity;
private string categoryID;
private string price;
private string itemName;
private string itemDesc;
private string itemImg;
private string inCart;
public FoodItem(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["orders"];
quantity = (string)jUser["Quantity"];
categoryID = (string)jUser["CategoryID"];
price = (string)jUser["Price"];
itemName =(string)jUser["itemDesc"];
itemImg = (string)jUser["itemImg"];
inCart = (string)jUser["inCart"];
}
}
I have tried to use this below from previous threads but still having an error message.
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[project.App_Code.FoodItem]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
var items = JsonConvert.DeserializeObject<List<FoodItem>>(strProductsInCart);