Я пытаюсь получить подробную информацию о продукте с помощью API Flipkart

Я не могу правильно преобразовать ответ JSON в класс, а затем отобразить в строке.

Это ответ:

    {
    "productBaseInfo": {
        "productIdentifier": {
            "productId": "SHODRYT32JN5N6WY",
            "categoryPaths": {
                "categoryPath": [
                    [
                        {
                            "title": "Footwear"
                        },
                        {
                            "title": "Men's Footwear"
                        },
                        {
                            "title": "Shoes"
                        },
                        {
                            "title": "Casual Shoes"
                        }
                    ]
                ]
            }
        },
        "productAttributes": {
            "title": "Diesel Magnete Exposure I Boots",
            "productDescription": null,
            "imageUrls": {
                "400x400": "url",
                "75x75": "url",
                "700x700": "url",
                "275x275": "url",
                "125x125": "url",
                "40x40": "url",
                "100x100": "url",
                "200x200": "url",
                "unknown": "http://img5a.flixcart.com/image/shoe/6/w/y/t7434-magnete-exposure-i-sneaker-mid-diesel-43-original-imadtxfxcgzkbzbg.jpeg",
                "180x240": "url",
                "275x340": "url"
            },
            "maximumRetailPrice": {
                "amount": 15800,
                "currency": "INR"
            },
            "sellingPrice": {
                "amount": 15800,
                "currency": "INR"
            },
            "productUrl": "http://dl.flipkart.com/dl/diesel-magnete-exposure-boots/p/itmdryt4zdzbwehx?pid=SHODRYT32JN5N6WY&affid=keviv2809",
            "productBrand": "Diesel",
            "inStock": true,
            "codAvailable": true,
            "emiAvailable": false,
            "discountPercentage": 0,
            "cashBack": null,
            "offers": [
                {
                    "title": "Get Flat 60% Off on this product"
                }
            ],
            "size": "44",
            "color": "Grey",
            "sizeUnit": "Euro",
            "sizeVariants": "[SHODRYT33YFFZHTU, SHODRYT3BZGFSBNV, SHODRYT3QECRQZ8Y, SHODRYT3QPQZG4XF, SHODRYT3Y5SUNHRM]",
            "colorVariants": "[SHODRYT3MVHPHVS2, SHODVN2YP5AXADT9, SHODVN2YUGUUGUST]",
            "styleCode": "MAGNETE EXPOSURE I - sneaker mid"
        }
    },
    "productShippingBaseInfo": {
        "shippingOptions": [
            {
                "estimatedDelivery": 3,
                "deliveryTimeUnits": "DAYS",
                "shippingType": "REGULAR"
            },
            {
                "estimatedDelivery": 1,
                "deliveryTimeUnits": "DAYS",
                "shippingType": "REGULAR"
            },
            {
                "estimatedDelivery": 0,
                "deliveryTimeUnits": "DAYS",
                "shippingType": "REGULAR"
            }
        ]
    },
    "offset": "v1:osp-cil-nit-e1f:SHODRYT32JN5N6WY"
}

Используемые мной классы:

public class CategoryPaths
{
    public List<ProductIdentifier> categoryPath { get; set; }
}

public class ProductIdentifier
{
    public string productId { get; set; }
    public CategoryPaths categoryPaths { get; set; }
}

public class ImageUrls
{
    public string 400x400 { get; set; }
    public string 125x167 { get; set; }
    public string 75x75 { get; set; }
    public string 700x700 { get; set; }
    public string 275x275 { get; set; }
    public string 125x125 { get; set; }
    public string 40x40 { get; set; }
    public string 100x100 { get; set; }
    public string 200x200 { get; set; }
    public string 1100x1360 { get; set; }
    public string unknown { get; set; }
    public string 180x240 { get; set; }
    public string 275x340 { get; set; }
}

public class MaximumRetailPrice
{
    public double amount { get; set; }
    public string currency { get; set; }
}

public class SellingPrice
{
    public double amount { get; set; }
    public string currency { get; set; }
}

public class Offer
{
    public string title { get; set; }
}

public class ProductAttributes
{
    public string title { get; set; }
    public object productDescription { get; set; }
    public ImageUrls imageUrls { get; set; }
    public MaximumRetailPrice maximumRetailPrice { get; set; }
    public SellingPrice sellingPrice { get; set; }
    public string productUrl { get; set; }
    public string productBrand { get; set; }
    public bool inStock { get; set; }
    public bool codAvailable { get; set; }
    public bool emiAvailable { get; set; }
    public double discountPercentage { get; set; }
    public object cashBack { get; set; }
    public List<Offer> offers { get; set; }
    public string size { get; set; }
    public string color { get; set; }
    public string sizeUnit { get; set; }
    public string sizeVariants { get; set; }
    public string colorVariants { get; set; }
    public string styleCode { get; set; }
}

public class ProductBaseInfo
{
    public ProductIdentifier productIdentifier { get; set; }
    public ProductAttributes productAttributes { get; set; }
}

public class ShippingOption
{
    public int estimatedDelivery { get; set; }
    public string deliveryTimeUnits { get; set; }
    public string shippingType { get; set; }
}

public class ProductShippingBaseInfo
{
    public List<ShippingOption> shippingOptions { get; set; }
}

public class RootObject
{
    public ProductBaseInfo productBaseInfo { get; set; }
    public ProductShippingBaseInfo productShippingBaseInfo { get; set; }
    public string offset { get; set; }
}

Я использую следующий код для десериализации его и затем цикл foreach для его отображения.

CategoryPaths pi = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<CategoryPaths>(json);

Я получаю следующую ошибку:

В экземпляре объекта не задана ссылка на объект.

Я думаю, что я ошибаюсь при использовании десериализации (метод) Кто-то, пожалуйста, помогите

[Edit]: я получил правильный метод десериализации, используя следующий код:

var dynJson = JsonConvert.DeserializeObject<RootObject>(json); Label1.Text = dynJson.productBaseInfo.productAttributes.maximumRetailPrice.amount.ToString()

Я не могу сохранить ответ json со значением "400X400":"url" в строке, так как он не позволяет мне объявить строковую переменную с именем 400X400

1 ответ

Определенный тип не соответствует структуре Json. Вы можете использовать приведенный ниже код для динамической десериализации и получить представление о структуре

using System.Web.Script.Serialization;

string json = "{\"productBaseInfo\":{\"productIdentifier\":{\"productId\":\"SHODRYT32JN5N6WY\",\"categoryPaths\":{\"categoryPath\":[[{\"title\":\"Footwear\"},{\"title\":\"Men's Footwear\"},{\"title\":\"Shoes\"},{\"title\":\"Casual Shoes\"}]]}},\"productAttributes\":{\"title\":\"Diesel Magnete Exposure I Boots\",\"productDescription\":null,\"imageUrls\":{\"400x400\":\"\",\"url\":\"url\",\"75x75\":\"url\",\"700x700\":\"url\",\"275x275\":\"url\",\"125x125\":\"url\",\"40x40\":\"url\",\"100x100\":\"url\",\"200x200\":\"\",\"url\":\"url\",\"unknown\":\"http://img5a.flixcart.com/image/shoe/6/w/y/t7434-magnete-exposure-i-sneaker-mid-diesel-43-original-imadtxfxcgzkbzbg.jpeg\",\"180x240\":\"url\",\"275x340\":\"url\"},\"maximumRetailPrice\":{\"amount\":15800.0,\"currency\":\"INR\"},\"sellingPrice\":{\"amount\":15800.0,\"currency\":\"INR\"},\"productUrl\":\"http://dl.flipkart.com/dl/diesel-magnete-exposure-boots/p/itmdryt4zdzbwehx?pid=SHODRYT32JN5N6WY&affid=keviv2809\",\"productBrand\":\"Diesel\",\"inStock\":true,\"codAvailable\":true,\"emiAvailable\":false,\"discountPercentage\":0.0,\"cashBack\":null,\"offers\":[{\"title\":\"Get Flat 60% Off on this product\"}],\"size\":\"44\",\"color\":\"Grey\",\"sizeUnit\":\"Euro\",\"sizeVariants\":\"[SHODRYT33YFFZHTU, SHODRYT3BZGFSBNV, SHODRYT3QECRQZ8Y, SHODRYT3QPQZG4XF, SHODRYT3Y5SUNHRM]\",\"colorVariants\":\"[SHODRYT3MVHPHVS2, SHODVN2YP5AXADT9, SHODVN2YUGUUGUST]\",\"styleCode\":\"MAGNETE EXPOSURE I - sneaker mid\"}},\"productShippingBaseInfo\":{\"shippingOptions\":[{\"estimatedDelivery\":3,\"deliveryTimeUnits\":\"DAYS\",\"shippingType\":\"REGULAR\"},{\"estimatedDelivery\":1,\"deliveryTimeUnits\":\"DAYS\",\"shippingType\":\"REGULAR\"},{\"estimatedDelivery\":0,\"deliveryTimeUnits\":\"DAYS\",\"shippingType\":\"REGULAR\"}]},\"offset\":\"v1:osp-cil-nit-e1f:SHODRYT32JN5N6WY\"}";

dynamic value = new JavaScriptSerializer().DeserializeObject(json);
Другие вопросы по тегам