Десериализовать JSON в объект (VB.NET) - PullRequest
2 голосов
/ 13 сентября 2011

У меня проблема с получением некоторых значений с помощью этой строки 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

Ответы [ 2 ]

1 голос
/ 14 сентября 2011

Я бы порекомендовал JSON.net, как SBlackler.Я написал тест на C #, основанный на ваших объектах и ​​объекте JSON, который вы опубликовали, и сумел построить все нормально.Вот мой код.

        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, но кадастры представляются массивом.В приведенном вами примере оказалось, что вы пытаетесь получить значение «цена» первого объекта внутри этого массива, и мой код делает это.Если в массиве инвентаризации есть несколько объектов, вы можете настроить свои объекты и код, который их заполняет соответствующим образом.

Вот мои объекты:

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; }
}

Надеюсь, это решит то, что вы искализа.Удачи!

1 голос
/ 14 сентября 2011

Вы смотрели на 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

Примечание: Мой пример может быть слегка отключен, не проверен синтаксисэто:)

...