JSON для Datagridview не работает в моем случае С#

У меня есть один 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;

Other than that i have also checked API is returning result successfully in the string which is "ScrapedResult"]

Результат, который я получаю в datagridview, выглядит примерно так: JSON для Datagridview не работает в моем случае С#

Так что я могу сделать, кроме того, что кто-то помочь мне с этим? 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
}]
}

Уровень вопроса 0: содержит ли переменная stores данные после вызова JsonConvert.DeserializeObject? Уровень вопроса 1: как насчет dataGridViewScrapedData.DataSource = stores.items;? Но будьте осторожны: API возвращает результат с разбивкой на страницы. Это может быть проблемой для вас, чтобы решить. Может быть, вы можете получить все сразу, но это тоже может быть слишком много.

ZorgoZ 04.03.2019 20:23

Уровень ответа 0: магазины имеют count = 0после звонка JsonConvert.DeserializeObject

Baig 05.03.2019 05:10

Уровень ответа 1: dataGridViewScrapedData.DataSource = stores.items не сработало.

Baig 05.03.2019 05:11

Судя по опубликованному коду… я не уверен, чего вы ожидаете. Строка List<RootObject> stores = new List<RootObject>(); … создает новый «пустой» список RootObjects. …. Затем строка… JsonConvert.DeserializeObject<RootObject>(ScrapedResult);… кажется, ничего не делает, поскольку эта строка «должна» возвращать десериализованный RootObject, но она ничему не присваивается. Кроме того, неизвестно, что такое ScrapedResult. И, наконец, установка DataSource на сетку…. dataGridViewScrapedData.DataSource = stores; кажется правильным, поскольку stores — «пустой» список.

JohnG 05.03.2019 05:36

@JohnG, ты можешь сказать мне, как это можно сделать?

Baig 05.03.2019 08:19

@голубой. Вы хотите перечислить элементы в вашем GridView?

Mahdi 05.03.2019 15:10

да @Mahdi ты можешь помочь мне с этим?

Baig 05.03.2019 19:42
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
7
234
1

Ответы 1

Обратите внимание, что вам нужно заполнить 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.

Другие вопросы по теме