【问题标题】:Deserialize JSON into an object (VB.NET)将 JSON 反序列化为对象 (VB.NET)
【发布时间】:2011-11-16 10:37:23
【问题描述】:

我在使用这个 json 字符串获取一些值时遇到问题:

{
 "kind": "shopping#products",
 "etag": "\"YZWJaKE3MHROIW8rCIlu9mAACLM/6qxBB-GwuSPy5L3_zVS6sS2NYFI\"",
 "id": "tag:google.com,2010:shopping/products",
 "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&q=Bauerfeind+MalleoTrain+Ankle+Support,+Circumference+in+inches+6+3/4+-+7+1/2+,+Left,+Color+Titanium+&rankBy=price:descending&maxResults=1&startIndex=1",
 "nextLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&q=Bauerfeind+MalleoTrain+Ankle+Support,+Circumference+in+inches+6+3/4+-+7+1/2+,+Left,+Color+Titanium+&rankBy=price:descending&maxResults=1&startIndex=2",
 "totalItems": 46,
 "startIndex": 1,
 "itemsPerPage": 1,
 "currentItemCount": 1,
 "items": [
  {
   "kind": "shopping#product",
   "id": "tag:google.com,2010:shopping/products/5944931/17136892246969389705",
   "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/5944931/gid/17136892246969389705",
   "product": {
        "googleId": "17136892246969389705",
        "author": {"name": "Superemployee.com","accountId": "5944931"},
        "creationTime": "2011-08-28T07:46:29.000Z",
        "modificationTime": "2011-09-11T06:02:54.000Z",
        "country": "US",
        "language": "en",
        "title": "Bauerfeind MalleoTrain Ankle Support Circumference in inches 6 3/4 - 7 1/2 Left Color Black",
        "description": "Bauerfeind MalleoTrain Ankle Support Circumference in inches 6 3/4 - 7 1/2 Left Color Black : Bauerfeind MalleoTrain Ankle Support, Circumference in inches 6 3/4 - 7 1/2 , Left, Color Black MalleoTrain relieves ankle pain and swelling during sports and everyday activities. Product Features: Knitted ankle support incorporating an anatomically contoured silicone insert behind each ankle bone . Silicone inserts leave ankle bones pressure-free and provide intermittent compression to the soft tissue of the joint, leading to increased circulation, thus aiding in the reduction of swelling and edema . Promotes proprioception , thus heightening sensory awareness in the ankle for increased joint stabilization . Anatomical knit carries controlled compression graduated at the edges to prevent constriction of circulation . Lightweight, breathable knit will not retain heat and is completely machine washable . Can be used to treat: Ankle swelling and soreness . Ankle sprains . Ligamental weakness and slight ligamentous tears . Degenerative joint disease (osteoarthritis) . Synovitis . ? Bursitis . Arthritis, osteoarthritis . Post cast . Product photo may not exactly match the product offered for sale. Please refer to the product description.",
        "link": "http://superemployee-com.amazonwebstore.com/Bauerfeind-MalleoTrain-Ankle-Support-Circumference-in/M/B001D0PFRY.htm?traffic_src=froogle&utm_medium=CSE&utm_source=froogle",
        "brand": "Bauerfeind",
        "condition": "new",
        "inventories": [{"channel": "online", "availability": "inStock","price": 90.0,"currency": "USD"} ],
        "images": [{"link": "http://ecx.images-amazon.com/images/I/31xD5bPI4sL.jpg?gdapi"}
    ]
   }
  }
 ]

我尝试过使用和创建类,但除了前两个级别之外无法返回数据,例如我试图检索价格但不知道如何提取这些数据?

这是我正在使用的代码,它什么也不返回:

<DataContract(Namespace:="")> _
    Public Class items

        <DataMember(Name:="product")>
        Public Property product As product

    End Class

    <DataContract(Name:="product", Namespace:="")> _
    Public Class product
        <DataMember(Name:="inventories")>
        Public Property inventories As inventories

    End Class

    <DataContract(Name:="inventories", Namespace:="")> _
    Public Class inventories
        <DataMember(Name:="price")>
        Public Property price As Double

    End Class

感谢您的帮助

使用 JSON.net 框架,我将我的类更改为以下,但仍然没有得到任何回报?

   Public Class items
        Public Property product As product()
        Public Property kind As String
    End Class

    Public Class product
        Public Property inventories As inventories()
    End Class

    Public Class inventories
        Public Property price As Double
    End Class

【问题讨论】:

    标签: .net vb.net json deserialization


    【解决方案1】:

    我会推荐 JSON.net,就像 SBlackler 所做的那样。我根据您的对象和您发布的 JSON 对象用 C# 编写了一个测试,并且能够构建一切正常。这是我的代码。

            List<items> Results = new List<items>();
            foreach (JToken Item in (JArray)JObject.Parse(json)["items"])
            {
                Results.Add(new items()
                {
                    kind = Item["kind"].ToString(),
                    product = new product()
                    {
                        inventories = new inventories()
                        {
                            price = Convert.ToDouble(Item["product"]["inventories"][0]["price"].ToString())
                        }
                    }
                });
            }
            Response.Write(Results[0].product.inventories.price);
    

    我有点不确定 json 对象的结构,但 inventory 似乎是一个数组。在您发布的示例中,您似乎试图获取该数组中第一个对象的“价格”值,而我的代码就是这样做的。如果库存数组中有多个对象,您可能需要相应地调整对象和填充它们的代码。

    这是我的对象:

    class items
    {
        public product product { get; set; }
        public string kind { get; set; }
    }
    
    class product
    {
        public inventories inventories { get; set; }
    }
    
    class inventories
    {
        public double price { get; set; }
    }
    

    上面的代码假定库存数组中总是至少有一个对象,并且只会从第一个对象中提取。如果库存数组中有多个对象,您可能希望如何重构代码。

        List<item> Results = new List<item>();
        foreach (JToken Item in (JArray)JObject.Parse(json)["items"])
        {
            item CurrentItem = new item()
            {
                kind = Item["kind"].ToString(),
                product = new product()
            };
            foreach (JToken inventory in (JArray)Item["product"]["inventories"])
            {
                CurrentItem.product.inventories.Add(new inventory()
                {
                    price = Convert.ToDouble(inventory["price"].ToString())
                });
            }
            Results.Add(CurrentItem);
        }
        Response.Write(Results[0].product.inventories[0].price);
    

    以及修改后的对象

    class item
    {
        public product product { get; set; }
        public string kind { get; set; }
    }
    
    class product
    {
        public List<inventory> inventories { get; set; }
    
        public product()
        {
            inventories = new List<inventory>();
        }
    }
    
    class inventory
    {
        public double price { get; set; }
    }
    

    我希望这能解决您正在寻找的问题。祝你好运!

    【讨论】:

    • 感谢您,它完美运行 :-) 我想要它在 VB.net 中,但很容易转换。谢谢
    • 对不起!我最初尝试用VB来做,但我的脑子就是不能用VB,哈哈,所以我就按我的方式写了。顺便说一句,如果你想要的话,给我那个检查标记的东西 =D
    • 别担心,我已经给你打勾了
    • 哦,如果可以的话,最后一点帮助,使用您的代码,我试图获取保存在“链接”字段中但无法完全正常工作的数据,我创建了在类产品中为其创建一个新条目,但无法在 for each 循环中访问它。
    • Scratch 我已经弄清楚了,在尝试获取链接值时缺少 [products] 的括号。
    【解决方案2】:

    你看过 JSON.net 吗?

    这是一个非常快速的序列化/反序列化框架。放入您的项目后,您可以执行以下操作:

    Dim myObj as <Enter object type> _
    = JsonConvert.DeserializeObject(Of <Enter object type>)("my json string here")
    

    首页为:http://james.newtonking.com/pages/json-net.aspx

    注意:我的例子可能有点偏离,没有检查它的语法:)

    【讨论】:

    • 有趣的是,我开始使用 JSON.net 框架,但仍然无法访问 Price 部分,我可以使用它来获取最高级别​​的信息,但是当我调用另一个类时没有带回信息?
    猜你喜欢
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多