首页 > 解决方案 > 如何创建一个基本 JSON 模式类来处理自定义数据类型作为响应?

问题描述

我正在创建一个库包装器来处理这个足球网站API的所有请求。当我调用端点时,会返回此响应结构:

{
    "get": "countries",
    "parameters": [],
    "errors": [],
    "results": 161,
    "paging": {
        "current": 1,
        "total": 1
    },
    "response": [
        {
            "name": "Albania",
            "code": "AL",
            "flag": "https://media.api-sports.io/flags/al.svg"
        },
        {
            "name": "Algeria",
            "code": "DZ",
            "flag": "https://media.api-sports.io/flags/dz.svg"
        },
        {
            "name": "Andorra",
            "code": "AD",
            "flag": "https://media.api-sports.io/flags/ad.svg"
        },
    ]
}

上面的示例是/countries端点。我使用Quicktype来生成模式结构,我得到了这个:

using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace FootballAPI.Models
{
    public partial class Temperatures
    {
        [JsonProperty("get")]
        public string Get { get; set; }

        [JsonProperty("parameters")]
        public object[] Parameters { get; set; }

        [JsonProperty("errors")]
        public object[] Errors { get; set; }

        [JsonProperty("results")]
        public long Results { get; set; }

        [JsonProperty("paging")]
        public Paging Paging { get; set; }

        [JsonProperty("response")]
        public Response[] Response { get; set; }
    }

    public partial class Paging
    {
        [JsonProperty("current")]
        public long Current { get; set; }

        [JsonProperty("total")]
        public long Total { get; set; }
    }

    public partial class Response
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("flag")]
        public Uri Flag { get; set; }
    }
}

我想要做的是有一个基本结构模式,其中包含除response属性之外的所有内容。在上面的例子response中必须是一个实例,Country它是:

public class Country 
{
    public string name { get; set; }
    public string code { get; set; }
    public string flag { get; set; }
}

我怎样才能告诉上面的基本模式Country用作T对象?我应该能够正确解析所有内容Newtonsoft.JSON

JsonConvert.DeserializeObject<Country>;

在这种情况下,我有不同的方法,比如GetCountries()只传递查询字符串/countries。所以我知道当时我期望的具体类型"response"

标签: c#jsonjson.net

解决方案


试试这些课程


public class Country
{
    public string name { get; set; }
    public string code { get; set; }
    public string flag { get; set; }
}

public class Countries
{
    public string get { get; set; }
    public List<object> parameters { get; set; }
    public List<object> errors { get; set; }
    public int results { get; set; }
    public Paging paging { get; set; }
    public List<Country> response { get; set; }
}
public class Paging
{
    public int current { get; set; }
    public int total { get; set; }
}

您可以使用

JsonConvert.DeserializeObject<Countries>(json);

推荐阅读