首页 > 解决方案 > 无法将 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);

标签: c#asp.netjson

解决方案


这是因为您需要一个顶部的容器类,其中包含此订单列表作为其中的属性:

public class MyData
{
     public List<FoodItem> Orders { get; set; }
{

var data = JsonConvert.DeserializeObject<MyData>(strProductsInCart);
var items = data.Orders;

此外,请确保您具有与 JSON 中的名称匹配的公共属性。它们也可以是 Pascal 案例。


推荐阅读