json - 如何为嵌套的 JSON 响应设置模型类?

标签 json api dotnet-httpclient

我在 C# 应用程序中使用 HttpClient 来访问 Web API。我是这种网络 API 的新手(我通常做 WCF 服务)。

其中一个响应如下所示:

{
    "access_token": the access token,
    "scope": "read",
    "expires_in": seconds to expiry,
    "refresh_token": a refresh token
}

模型类如下所示:

class AuthResponse
{
    public string access_token { get; set; }
    public string scope { get; set; }
    public int expires_in { get; set; }
    public string refresh_token { get; set; }
}

所以当我这样做的时候:

var result = resposne.Content.ReadAsAsync<AuthResponse>().Result;

我得到一个填充了值的 AuthResponse 对象。神奇。

下一段 API 返回如下响应:

{
    "data": {
         "visible": boolean,
         "email": valid e-mail string or null,
         "location_string": human-readable location identifier string,
         "ad_id": primary key of the ad
    }, 
    "actions": {
         "change_form": URL to change this ad
         "public_view": URL to view this ad's public HTML page
         "html_edit": URL to view this ad's HTML edit page 
                      that has more options than the API change_form does
    }
}

我的模型类会是什么样子?我如何解释嵌套?

最佳答案

如果你现在还没有解决这个问题,这就是我发现的:

我发现这很棒:

http://json2csharp.com

您只需将您的 JSON url 或什至您的 JSON 粘贴到其中,它就会返回一个带有嵌套的模型类。或者,您可以在 Visual Studio 中复制 JSOn 和编辑 > 选择性粘贴 >,这也将返回您的模型类。

关于json - 如何为嵌套的 JSON 响应设置模型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17722742/

相关文章:

c++ - C++是否使用接口(interface)?

javascript - Angular JS 简单 API : only showing data that begins with the word 'request'

xml - mediawiki:获取给定类别中的页面

c# - System.Net.Http.HttpClient 实例在设置逗号时抛出异常。为什么?

c# - 为什么在使用 ObjectContent 时无法从 HttpClient SendAsync 捕获异常

c# - 无法将具有 JSON 内容的字符串反序列化为 C# 对象

c# - 使用 WebHttpBinding 通过 HTTP 从 SQL 传输表格数据的绝对最快方法

javascript - 格式化 JSON 时遇到问题

java - JsonNode isTextual() 莫名其妙地返回 false

json - Powershell 转换为 Json 格式错误