c# - 无法将 JSON 字符串转换为对象列表
问题描述
我有这个 JSON 字符串,我想将它转换为 C# asp.net 中的对象列表。
在 VS 中,我可以看到 json 字符串如下所示:
"{\"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}]}"
但在浏览器本地存储中,json 格式正确,如下所示:
{
"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
}
]
}
我想将它转换为 FoodItem 对象数组 list ,下面是类代码:
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"];
}
}
我曾尝试从以前的线程中使用它,但仍然有错误消息。
Newtonsoft.Json.JsonSerializationException:'无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[project.App_Code.FoodItem]',因为该类型需要正确反序列化的 JSON 数组(例如 [1,2,3])。
var items = JsonConvert.DeserializeObject<List<FoodItem>>(strProductsInCart);
解决方案
这是因为您需要一个顶部的容器类,其中包含此订单列表作为其中的属性:
public class MyData
{
public List<FoodItem> Orders { get; set; }
{
var data = JsonConvert.DeserializeObject<MyData>(strProductsInCart);
var items = data.Orders;
此外,请确保您具有与 JSON 中的名称匹配的公共属性。它们也可以是 Pascal 案例。
推荐阅读
- c# - 如何在 rdlc 报告中显示和设计列表列表
- c# - SharePoint CSOM 未在 ExecuteQuery 上引发预期异常
- json - 如何在 Flutter App 中使用 HTML 读取 JSON?
- .htaccess - 如何在 htaccess Xampp 中传递多个值
- python - 错误“强制转换为 Unicode:需要字符串或缓冲区,找到 cStringIO.StringO”当我尝试从 python 中的 url 插入 excel 图像时
- python - 是否有理由不总是使用leaky_relu
- c# - 有时方法在发布时没有在asp.net c#中执行
- java - Jackson 序列化 - 忽略未设置的值,但提供明确设置为 null 的值
- c++ - CMake 在 Windows 上的自定义位置上找不到 Boost
- sql - 当行不存在时插入表中,否则使用 Oracle SQL 更新表