JSON для Datagridview не работает в моем случае c # - PullRequest
0 голосов
/ 04 марта 2019

У меня есть один JSON после вызова API.Я перепробовал много методов для извлечения данных из JSON и затем связал их с datagridview, но каждый раз терпел неудачу.Поэтому я хочу, чтобы кто-то помог мне с этим.У меня есть класс JSON, полученный из http://json2csharp.com

public class Attributes
{
    public string color { get; set; }
    public string finerCateg { get; set; }
    public string mainimageurl { get; set; }
    public string productTaxCode { get; set; }
    public string productUrlText { get; set; }
    public string caResidentsPropWarningRequired { get; set; }
    public string prodClassType { get; set; }
    public string canonicalUrl { get; set; }
    public string compositeWood { get; set; }
    public string numOfBatt { get; set; }
    public string actualColor { get; set; }
    public string multipackQuantity { get; set; }
    public string size { get; set; }
    public string ironBankCategory { get; set; }
    public string isSortable { get; set; }
    public string replenishmentEndDate { get; set; }
    public string features { get; set; }
    public string gender { get; set; }
    public string simsInventoryType { get; set; }
    public string isPvtLabelUnbranded { get; set; }
    public string fuelRestriction { get; set; }
    public string hasWarranty { get; set; }
}

public class BestMarketplacePrice
{
    public double price { get; set; }
    public string sellerInfo { get; set; }
    public double standardShipRate { get; set; }
    public double twoThreeDayShippingRate { get; set; }
    public bool availableOnline { get; set; }
    public bool clearance { get; set; }
}

public class Item
{
    public int itemId { get; set; }
    public int parentItemId { get; set; }
    public string name { get; set; }
    public double msrp { get; set; }
    public double salePrice { get; set; }
    public string upc { get; set; }
    public string categoryPath { get; set; }
    public string shortDescription { get; set; }
    public string longDescription { get; set; }
    public string brandName { get; set; }
    public string thumbnailImage { get; set; }
    public string mediumImage { get; set; }
    public string largeImage { get; set; }
    public string productTrackingUrl { get; set; }
    public double standardShipRate { get; set; }
    public double twoThreeDayShippingRate { get; set; }
    public string color { get; set; }
    public bool marketplace { get; set; }
    public string modelNumber { get; set; }
    public string sellerInfo { get; set; }
    public string productUrl { get; set; }
    public string customerRating { get; set; }
    public int numReviews { get; set; }
    public string customerRatingImage { get; set; }
    public string categoryNode { get; set; }
    public string rhid { get; set; }
    public bool bundle { get; set; }
    public bool clearance { get; set; }
    public bool preOrder { get; set; }
    public string stock { get; set; }
    public Attributes attributes { get; set; }
    public string addToCartUrl { get; set; }
    public string affiliateAddToCartUrl { get; set; }
    public bool freeShippingOver35Dollars { get; set; }
    public bool availableOnline { get; set; }
    public string gender { get; set; }
    public bool? ninetySevenCentShipping { get; set; }
    public string size { get; set; }
    public bool? shipToStore { get; set; }
    public bool? freeShipToStore { get; set; }
    public BestMarketplacePrice bestMarketplacePrice { get; set; }
    public List<int?> variants { get; set; }
    public bool? freight { get; set; }
}

public class RootObject
{
    public string category { get; set; }
    public string brand { get; set; }
    public string format { get; set; }
    public string nextPage { get; set; }
    public string totalPages { get; set; }
    public List<Item> items { get; set; }
}

Код десериализации:

 List<RootObject> stores = new List<RootObject>();
RootObject ScrapedResult = JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(@"D:\Test\Data1.json"));
stores.Add(ScrapedResult);
dataGridViewScrapedData.DataSource = stores;

Кроме того, что я также проверил, API успешно возвращает результат в строке"ScrapedResult"]

Результат, который я получаю в таблице данных, выглядит примерно так: enter image description here

Так что же я могу сделать, кромечто кто-то поможет мне с этим?JSON это:

    {
"category": "5428_5593752_8341994",
"brand": "Patio",
"format": "json",
"nextPage": "/v1/paginated/items?category=5428_5593752_8341994&brand=Patio&maxId=999930884&apiKey=z8w2s244z3y4c6845uwqzc98",
"totalPages": "1",
"items": [{
    "itemId": 19345483,
    "parentItemId": 19345483,
    "name": "Tahti Outdoor Patio Table Umbrella Lamp",
    "msrp": 300.0,
    "salePrice": 172.2,
    "upc": "833353177774",
    "categoryPath": "Patio & Garden/Outdoor Shade/Patio Umbrellas/Patio Umbrella Accessories",
    "shortDescription": "Add light instead of shade to your patio table with the Thati Outdoor Patio Table Umbrella Lamp. This unique lamp accommodates most standard patio tables with an umbrella hole up to 3-inches. If your table sits in a spot where an umbrella isn't necessary, this is a unique and charming alternative. Constructed of weatherproof materials, starting with the all resin base in a dark bronze finish, this lamp is made for the outdoors. The shade is all-weather, hand-woven PVC wicker and is available in your choice of Walnut or Antique Honey. An unbreakable polycarbonate light bulb enclosure protects the standard 100 watt bulb (not included) from any damage. Some simple assembly is required. Patio Living Concepts Incorporating aesthetics, function, and quality from the initial design phase to the finished product, Patio Living Concepts excels in creative product design",
    "longDescription": ". Their design and engineering team balance these parameters with reliability, safety and durability in mind. They craft an unsurpassed level of quality into every product, and meticulous quality inspections ensure conformity of all components. Patio Living Concepts strives to offer the finest quality leisure and lighting products at prices that are globally competitive. They are backed by over 38 years of experience in product design and engineering in the lighting industry.",
    "brandName": "Patio Living Concepts",
    "thumbnailImage": "https://i5.walmartimages.com/asr/9ec4395d-be65-4636-b2ff-bce3df981f89_1.338332362d3de003ae37765ae406b543.jpeg?odnHeight=100&odnWidth=100&odnBg=ffffff",
    "mediumImage": "https://i5.walmartimages.com/asr/9ec4395d-be65-4636-b2ff-bce3df981f89_1.338332362d3de003ae37765ae406b543.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff",
    "largeImage": "https://i5.walmartimages.com/asr/9ec4395d-be65-4636-b2ff-bce3df981f89_1.338332362d3de003ae37765ae406b543.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff",
    "productTrackingUrl": "http://linksynergy.walmart.com/fs-bin/click?id=|LSNID|&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1082&RD_PARM1=https%253A%252F%252Fwww.walmart.com%252Fip%252FTahti-Outdoor-Patio-Table-Umbrella-Lamp%252F19345483%253Faffp1%253DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%2526affilsrc%253Dapi",
    "standardShipRate": 0.0,
    "twoThreeDayShippingRate": 170.0,
    "color": "Brown",
    "marketplace": true,
    "modelNumber": "17777",
    "sellerInfo": "Vir Ventures Inc.",
    "productUrl": "http://c.affil.walmart.com/t/api01?l=https%3A%2F%2Fwww.walmart.com%2Fip%2FTahti-Outdoor-Patio-Table-Umbrella-Lamp%2F19345483%3Faffp1%3DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner%3Dreadonlyapi",
    "customerRating": "5.0",
    "numReviews": 3,
    "customerRatingImage": "http://i2.walmartimages.com/i/CustRating/5.gif",
    "categoryNode": "5428_5593752_8341994",
    "rhid": "35360",
    "bundle": false,
    "clearance": false,
    "preOrder": false,
    "stock": "Not available",
    "attributes": {
        "color": "Brown",
        "finerCateg": "Patio Umbrella Accessories",
        "mainimageurl": "https://i5.walmartimages.com/asr/9ec4395d-be65-4636-b2ff-bce3df981f89_1.338332362d3de003ae37765ae406b543.jpeg"
    },
    "addToCartUrl": "http://c.affil.walmart.com/t/api01?l=http%3A%2F%2Faffil.walmart.com%2Fcart%2FaddToCart%3Fitems%3D19345483%7C1%26affp1%3DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner%3Dreadonlyapi",
    "affiliateAddToCartUrl": "http://linksynergy.walmart.com/fs-bin/click?id=|LSNID|&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1082&RD_PARM1=http%253A%252F%252Faffil.walmart.com%252Fcart%252FaddToCart%253Fitems%253D19345483%257C1%2526affp1%253DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%2526affilsrc%253Dapi",
    "freeShippingOver35Dollars": false,
    "availableOnline": false
}, {
    "itemId": 19393431,
    "parentItemId": 19345483,
    "name": "Tahti Outdoor Patio Table Umbrella Lamp",
    "msrp": 248.92,
    "salePrice": 202.99,
    "categoryPath": "Patio & Garden/Outdoor Shade/Patio Umbrellas/Patio Umbrella Accessories",
    "shortDescription": "Add light instead of shade to your patio table with the Thati Outdoor Patio Table Umbrella Lamp. This unique lamp accommodates most standard patio tables with an umbrella hole up to 3-inches. If your table sits in a spot where an umbrella isn't necessary, this is a unique and charming alternative. Constructed of weatherproof materials, starting with the all resin base in a dark bronze finish, this lamp is made for the outdoors. The shade is all-weather, hand-woven PVC wicker and is available in your choice of Walnut or Antique Honey. An unbreakable polycarbonate light bulb enclosure protects the standard 100 watt bulb (not included) from any damage. Some simple assembly is required. Patio Living Concepts Incorporating aesthetics, function, and quality from the initial design phase to the finished product, Patio Living Concepts excels in creative product design",
    "longDescription": ". Their design and engineering team balance these parameters with reliability, safety and durability in mind. They craft an unsurpassed level of quality into every product, and meticulous quality inspections ensure conformity of all components. Patio Living Concepts strives to offer the finest quality leisure and lighting products at prices that are globally competitive. They are backed by over 38 years of experience in product design and engineering in the lighting industry.",
    "brandName": "Patio Living Concepts",
    "thumbnailImage": "https://i5.walmartimages.com/asr/a245fff9-a843-498c-aa82-0b8554fd2059_1.23272356af2c7776abdd545d75739a7b.jpeg?odnHeight=100&odnWidth=100&odnBg=ffffff",
    "mediumImage": "https://i5.walmartimages.com/asr/a245fff9-a843-498c-aa82-0b8554fd2059_1.23272356af2c7776abdd545d75739a7b.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff",
    "largeImage": "https://i5.walmartimages.com/asr/a245fff9-a843-498c-aa82-0b8554fd2059_1.23272356af2c7776abdd545d75739a7b.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff",
    "productTrackingUrl": "http://linksynergy.walmart.com/fs-bin/click?id=|LSNID|&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1082&RD_PARM1=https%253A%252F%252Fwww.walmart.com%252Fip%252FTahti-Outdoor-Patio-Table-Umbrella-Lamp%252F19393431%253Faffp1%253DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%2526affilsrc%253Dapi",
    "standardShipRate": 0.0,
    "twoThreeDayShippingRate": 110.0,
    "color": "Yellow",
    "marketplace": true,
    "sellerInfo": "PlumStruck",
    "productUrl": "http://c.affil.walmart.com/t/api01?l=https%3A%2F%2Fwww.walmart.com%2Fip%2FTahti-Outdoor-Patio-Table-Umbrella-Lamp%2F19393431%3Faffp1%3DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner%3Dreadonlyapi",
    "categoryNode": "5428_5593752_8341994",
    "rhid": "35360",
    "bundle": false,
    "clearance": false,
    "stock": "Not available",
    "attributes": {
        "color": "Yellow",
        "productTaxCode": "2038345",
        "productUrlText": "/ip/Tahti-Outdoor-Patio-Table-Umbrella-Lamp/19393431"
    },
    "addToCartUrl": "http://c.affil.walmart.com/t/api01?l=http%3A%2F%2Faffil.walmart.com%2Fcart%2FaddToCart%3Fitems%3D19393431%7C1%26affp1%3DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner%3Dreadonlyapi",
    "affiliateAddToCartUrl": "http://linksynergy.walmart.com/fs-bin/click?id=|LSNID|&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1082&RD_PARM1=http%253A%252F%252Faffil.walmart.com%252Fcart%252FaddToCart%253Fitems%253D19393431%257C1%2526affp1%253DI_INcA8xpLiW736-BdxAlFeIaiqJmqmv0YtBPcyaPsk%2526affilsrc%253Dapi",
    "freeShippingOver35Dollars": false,
    "availableOnline": false
}]
}

1 Ответ

0 голосов
/ 06 марта 2019

Обратите внимание, что вам нужно заполнить DataSource списком объектов.В вашей строке JSON есть только один список: List<Item>.Теперь вы можете использовать этот список в качестве источника данных для вашего GridView следующим образом:

var path = @"C:\MyStuff\json.txt";
var json = File.ReadAllText(path);
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
var items = rootObject.items;
MyGridView.DataSource = items;
// MyGridView.DataBind();

Осталось только показать первую пару свойств, а именно, category, brand, format, nextPage и totalPages.Согласно вашему JSON они кажутся исправленными, и если это так, вы можете просто показать их за пределами GridView.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...