Десериализация с System.text.json. Не получается распарсить сложный json ответ с API?

Всем привет. С сервера приходит json ответ в виде:
{
    "status": {
        "timestamp": "2021-06-28T05:54:55.250Z",
        "error_code": 0,
        "error_message": null,
        "elapsed": 28,
        "credit_count": 1,
        "notice": null,
        "total_count": 5475
    },
    "data": [
        {
            "id": 1,
            "name": "Bitcoin",
            "symbol": "BTC",
            "slug": "bitcoin",
            "num_market_pairs": 9210,
            "date_added": "2013-04-28T00:00:00.000Z",
            "tags": [
                "mineable",
                "pow",
                "sha-256",
                "store-of-value",
                "state-channels",
                "coinbase-ventures-portfolio",
                "three-arrows-capital-portfolio",
                "polychain-capital-portfolio",
                "binance-labs-portfolio",
                "arrington-xrp-capital",
                "blockchain-capital-portfolio",
                "boostvc-portfolio",
                "cms-holdings-portfolio",
                "dcg-portfolio",
                "dragonfly-capital-portfolio",
                "electric-capital-portfolio",
                "fabric-ventures-portfolio",
                "framework-ventures",
                "galaxy-digital-portfolio",
                "huobi-capital",
                "alameda-research-portfolio",
                "a16z-portfolio",
                "1confirmation-portfolio",
                "winklevoss-capital",
                "usv-portfolio",
                "placeholder-ventures-portfolio",
                "pantera-capital-portfolio",
                "multicoin-capital-portfolio",
                "paradigm-xzy-screener"
            ],
            "max_supply": 21000000,
            "circulating_supply": 18743737,
            "total_supply": 18743737,
            "platform": null,
            "cmc_rank": 1,
            "last_updated": "2021-06-28T05:54:02.000Z",
            "quote": {
                "USD": {
                    "price": 34489.91295375669,
                    "volume_24h": 33231566302.9618,
                    "percent_change_1h": 0.24623143,
                    "percent_change_24h": 4.72866241,
                    "percent_change_7d": 0.0385825,
                    "percent_change_30d": -6.57806083,
                    "percent_change_60d": -36.08177402,
                    "percent_change_90d": -40.16259997,
                    "market_cap": 646469857558.1086,
                    "last_updated": "2021-06-28T05:54:02.000Z"
                }
            }
        },
        {
            "id": 1027,
            "name": "Ethereum",
            "symbol": "ETH",
            "slug": "ethereum",
            "num_market_pairs": 6005,
            "date_added": "2015-08-07T00:00:00.000Z",
            "tags": [
                "mineable",
                "pow",
                "smart-contracts",
                "ethereum",
                "coinbase-ventures-portfolio",
                "three-arrows-capital-portfolio",
                "polychain-capital-portfolio",
                "binance-labs-portfolio",
                "arrington-xrp-capital",
                "blockchain-capital-portfolio",
                "boostvc-portfolio",
                "cms-holdings-portfolio",
                "dcg-portfolio",
                "dragonfly-capital-portfolio",
                "electric-capital-portfolio",
                "fabric-ventures-portfolio",
                "framework-ventures",
                "hashkey-capital-portfolio",
                "kinetic-capital",
                "huobi-capital",
                "alameda-research-portfolio",
                "a16z-portfolio",
                "1confirmation-portfolio",
                "winklevoss-capital",
                "usv-portfolio",
                "placeholder-ventures-portfolio",
                "pantera-capital-portfolio",
                "multicoin-capital-portfolio",
                "paradigm-xzy-screener"
            ],
            "max_supply": null,
            "circulating_supply": 116469137.499,
            "total_supply": 116469137.499,
            "platform": null,
            "cmc_rank": 2,
            "last_updated": "2021-06-28T05:54:02.000Z",
            "quote": {
                "USD": {
                    "price": 1972.9974245462824,
                    "volume_24h": 19489435867.08539,
                    "percent_change_1h": -0.03164063,
                    "percent_change_24h": 5.36554092,
                    "percent_change_7d": -7.36312666,
                    "percent_change_30d": -22.4570674,
                    "percent_change_60d": -27.41396336,
                    "percent_change_90d": 9.21290472,
                    "market_cap": 229793308324.65384,
                    "last_updated": "2021-06-28T05:54:02.000Z"
                }
            }
        },
        {
            "id": 825,
            "name": "Tether",
            "symbol": "USDT",
            "slug": "tether",
            "num_market_pairs": 13711,
            "date_added": "2015-02-25T00:00:00.000Z",
            "tags": [
                "payments",
                "stablecoin",
                "stablecoin-asset-backed",
                "solana-ecosystem"
            ],
            "max_supply": null,
            "circulating_supply": 62534142511.11169,
            "total_supply": 64471767616.826355,
            "platform": {
                "id": 1027,
                "name": "Ethereum",
                "symbol": "ETH",
                "slug": "ethereum",
                "token_address": "0xdac17f958d2ee523a2206206994597c13d831ec7"
            },
            "cmc_rank": 3,
            "last_updated": "2021-06-28T05:53:08.000Z",
            "quote": {
                "USD": {
                    "price": 1.00023604778902,
                    "volume_24h": 50665651395.52314,
                    "percent_change_1h": -0.00327685,
                    "percent_change_24h": -0.11177658,
                    "percent_change_7d": -0.14175554,
                    "percent_change_30d": -0.07861614,
                    "percent_change_60d": 0.01010439,
                    "percent_change_90d": -0.01064075,
                    "market_cap": 62548903557.1897,
                    "last_updated": "2021-06-28T05:53:08.000Z"
                }
            }
        },
        {
            "id": 1839,
            "name": "Binance Coin",
            "symbol": "BNB",
            "slug": "binance-coin",
            "num_market_pairs": 570,
            "date_added": "2017-07-25T00:00:00.000Z",
            "tags": [
                "marketplace",
                "centralized-exchange",
                "payments",
                "binance-smart-chain",
                "alameda-research-portfolio",
                "multicoin-capital-portfolio"
            ]
}
//И ТАК ДАЛЕЕ

Мне необходимо распарсить это в C# ассоциированную модель :
public class ModelJson
    {
        [JsonPropertyName("data")]
        public Base[] Data { get; set; }
    }
    public class Base
    {
        [JsonPropertyName("id")]
        public int Id { get; set; }
        [JsonPropertyName("name")]
        public string Name { get; set; }
        [JsonPropertyName("slug")]
        public string Slug { get; set; }
        [JsonPropertyName("symbol")]
        public string Symbol { get; set; }
        [JsonPropertyName("quote")]
        public Dictionary<string, USD> Quote { get; set; }
        
    }
    public class USD 
    {
        [JsonPropertyName("price")]
        public decimal Price { get; set; }
        [JsonPropertyName("percent_change_1h")]
        public decimal ChangesHour { get; set; }
        [JsonPropertyName("percent_change_24h")]
        public decimal ChangesDay { get; set; }
        [JsonPropertyName("percent_change_7d")]
        public decimal ChangesWeek { get; set; }
        [JsonPropertyName("market_cap")]
        public decimal MarketCap { get; set; }
        [JsonPropertyName("last_updated")]
        public string LastUpdated { get; set; }
    }
}
Помогите решить задачу... Нужно это распарсить в массив.
  • Вопрос задан
  • 64 просмотра
Решения вопроса 1
vabka
@vabka Куратор тега C#
Токсичный шарпист
1. Пропустил скобочки:
Вот такой json должен быть

{
  "status": {
    "timestamp": "2021-06-28T05:54:55.250Z",
    "error_code": 0,
    "elapsed": 28,
    "credit_count": 1,
    "total_count": 5475
  },
  "data": [
    {
      "id": 1,
      "name": "Bitcoin",
      "symbol": "BTC",
      "slug": "bitcoin",
      "num_market_pairs": 9210,
      "date_added": "2013-04-28T00:00:00.000Z",
      "tags": [
        "mineable",
        "pow",
        "sha-256",
        "store-of-value",
        "state-channels",
        "coinbase-ventures-portfolio",
        "three-arrows-capital-portfolio",
        "polychain-capital-portfolio",
        "binance-labs-portfolio",
        "arrington-xrp-capital",
        "blockchain-capital-portfolio",
        "boostvc-portfolio",
        "cms-holdings-portfolio",
        "dcg-portfolio",
        "dragonfly-capital-portfolio",
        "electric-capital-portfolio",
        "fabric-ventures-portfolio",
        "framework-ventures",
        "galaxy-digital-portfolio",
        "huobi-capital",
        "alameda-research-portfolio",
        "a16z-portfolio",
        "1confirmation-portfolio",
        "winklevoss-capital",
        "usv-portfolio",
        "placeholder-ventures-portfolio",
        "pantera-capital-portfolio",
        "multicoin-capital-portfolio",
        "paradigm-xzy-screener"
      ],
      "max_supply": 21000000,
      "circulating_supply": 18743737,
      "total_supply": 18743737,
      "cmc_rank": 1,
      "last_updated": "2021-06-28T05:54:02.000Z",
      "quote": {
        "USD": {
          "price": 34489.91295375669,
          "volume_24h": 33231566302.9618,
          "percent_change_1h": 0.24623143,
          "percent_change_24h": 4.72866241,
          "percent_change_7d": 0.0385825,
          "percent_change_30d": -6.57806083,
          "percent_change_60d": -36.08177402,
          "percent_change_90d": -40.16259997,
          "market_cap": 646469857558.1086,
          "last_updated": "2021-06-28T05:54:02.000Z"
        }
      }
    },
    {
      "id": 1027,
      "name": "Ethereum",
      "symbol": "ETH",
      "slug": "ethereum",
      "num_market_pairs": 6005,
      "date_added": "2015-08-07T00:00:00.000Z",
      "tags": [
        "mineable",
        "pow",
        "smart-contracts",
        "ethereum",
        "coinbase-ventures-portfolio",
        "three-arrows-capital-portfolio",
        "polychain-capital-portfolio",
        "binance-labs-portfolio",
        "arrington-xrp-capital",
        "blockchain-capital-portfolio",
        "boostvc-portfolio",
        "cms-holdings-portfolio",
        "dcg-portfolio",
        "dragonfly-capital-portfolio",
        "electric-capital-portfolio",
        "fabric-ventures-portfolio",
        "framework-ventures",
        "hashkey-capital-portfolio",
        "kinetic-capital",
        "huobi-capital",
        "alameda-research-portfolio",
        "a16z-portfolio",
        "1confirmation-portfolio",
        "winklevoss-capital",
        "usv-portfolio",
        "placeholder-ventures-portfolio",
        "pantera-capital-portfolio",
        "multicoin-capital-portfolio",
        "paradigm-xzy-screener"
      ],
      "circulating_supply": 116469137.499,
      "total_supply": 116469137.499,
      "cmc_rank": 2,
      "last_updated": "2021-06-28T05:54:02.000Z",
      "quote": {
        "USD": {
          "price": 1972.9974245462824,
          "volume_24h": 19489435867.08539,
          "percent_change_1h": -0.03164063,
          "percent_change_24h": 5.36554092,
          "percent_change_7d": -7.36312666,
          "percent_change_30d": -22.4570674,
          "percent_change_60d": -27.41396336,
          "percent_change_90d": 9.21290472,
          "market_cap": 229793308324.65384,
          "last_updated": "2021-06-28T05:54:02.000Z"
        }
      }
    },
    {
      "id": 825,
      "name": "Tether",
      "symbol": "USDT",
      "slug": "tether",
      "num_market_pairs": 13711,
      "date_added": "2015-02-25T00:00:00.000Z",
      "tags": [
        "payments",
        "stablecoin",
        "stablecoin-asset-backed",
        "solana-ecosystem"
      ],
      "circulating_supply": 62534142511.11169,
      "total_supply": 64471767616.826355,
      "platform": {
        "id": 1027,
        "name": "Ethereum",
        "symbol": "ETH",
        "slug": "ethereum",
        "token_address": "0xdac17f958d2ee523a2206206994597c13d831ec7"
      },
      "cmc_rank": 3,
      "last_updated": "2021-06-28T05:53:08.000Z",
      "quote": {
        "USD": {
          "price": 1.00023604778902,
          "volume_24h": 50665651395.52314,
          "percent_change_1h": -0.00327685,
          "percent_change_24h": -0.11177658,
          "percent_change_7d": -0.14175554,
          "percent_change_30d": -0.07861614,
          "percent_change_60d": 0.01010439,
          "percent_change_90d": -0.01064075,
          "market_cap": 62548903557.1897,
          "last_updated": "2021-06-28T05:53:08.000Z"
        }
      }
    },
    {
      "id": 1839,
      "name": "Binance Coin",
      "symbol": "BNB",
      "slug": "binance-coin",
      "num_market_pairs": 570,
      "date_added": "2017-07-25T00:00:00.000Z",
      "tags": [
        "marketplace",
        "centralized-exchange",
        "payments",
        "binance-smart-chain",
        "alameda-research-portfolio",
        "multicoin-capital-portfolio"
      ]
    }
  ]
}


2. После генерации нужно ещё руками подкорректировать классы:
- Переименовать классы (например Root на Response)
- Поменять типы (например double на decimal)
- Дополнить недостающее. (Например Quote заменить на словарь)
Код

using System.Text.Json;
using System.Text.Json.Serialization;

public class Status
{
    [JsonPropertyName("timestamp")]
    public DateTime Timestamp { get; set; }

    [JsonPropertyName("error_code")]
    public int ErrorCode { get; set; }

    [JsonPropertyName("elapsed")]
    public int Elapsed { get; set; }

    [JsonPropertyName("credit_count")]
    public int CreditCount { get; set; }

    [JsonPropertyName("total_count")]
    public int TotalCount { get; set; }
}

public class QuoteForCurrency
{
    [JsonPropertyName("price")]
    public decimal Price { get; set; }

    [JsonPropertyName("volume_24h")]
    public decimal Volume24h { get; set; }

    [JsonPropertyName("percent_change_1h")]
    public decimal PercentChange1h { get; set; }

    [JsonPropertyName("percent_change_24h")]
    public decimal PercentChange24h { get; set; }

    [JsonPropertyName("percent_change_7d")]
    public decimal PercentChange7d { get; set; }

    [JsonPropertyName("percent_change_30d")]
    public decimal PercentChange30d { get; set; }

    [JsonPropertyName("percent_change_60d")]
    public decimal PercentChange60d { get; set; }

    [JsonPropertyName("percent_change_90d")]
    public decimal PercentChange90d { get; set; }

    [JsonPropertyName("market_cap")]
    public decimal MarketCap { get; set; }

    [JsonPropertyName("last_updated")]
    public DateTime LastUpdated { get; set; }
}

public class Platform
{
    [JsonPropertyName("id")]
    public int Id { get; set; }

    [JsonPropertyName("name")]
    public string Name { get; set; }

    [JsonPropertyName("symbol")]
    public string Symbol { get; set; }

    [JsonPropertyName("slug")]
    public string Slug { get; set; }

    [JsonPropertyName("token_address")]
    public string TokenAddress { get; set; }
}

public class Item
{
    [JsonPropertyName("id")]
    public int Id { get; set; }

    [JsonPropertyName("name")]
    public string Name { get; set; }

    [JsonPropertyName("symbol")]
    public string Symbol { get; set; }

    [JsonPropertyName("slug")]
    public string Slug { get; set; }

    [JsonPropertyName("num_market_pairs")]
    public int NumMarketPairs { get; set; }

    [JsonPropertyName("date_added")]
    public DateTime DateAdded { get; set; }

    [JsonPropertyName("tags")]
    public List<string> Tags { get; set; }

    [JsonPropertyName("max_supply")]
    public int MaxSupply { get; set; }

    [JsonPropertyName("circulating_supply")]
    public decimal CirculatingSupply { get; set; }

    [JsonPropertyName("total_supply")]
    public decimal TotalSupply { get; set; }

    [JsonPropertyName("cmc_rank")]
    public int CmcRank { get; set; }

    [JsonPropertyName("last_updated")]
    public DateTime LastUpdated { get; set; }

    [JsonPropertyName("quote")]
    public Dictionary<string, QuoteForCurrency> Quote { get; set; }

    [JsonPropertyName("platform")]
    public Platform Platform { get; set; }
}

public class Response
{
    [JsonPropertyName("status")]
    public Status Status { get; set; }

    [JsonPropertyName("data")]
    public List<Item> Data { get; set; }
}


3. Тогда чтобы спарсить ответ надо будет просто написать код:
var json = "{}"; // тут твой ответ json из ответа
var responseData = JsonSerializer.Deserialize<Response>(json);
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы