【问题标题】:Automatically serialize a JSON server response with JSON.net [closed]使用 JSON.net 自动序列化 JSON 服务器响应 [关闭]
【发布时间】:2018-12-14 20:36:03
【问题描述】:

学习 C#。我正在使用 JSON.net 序列化和反序列化服务器的响应。

我确实有一小部分在工作。例如,对于 OAuth2,我需要发送凭据以获取 access_token。我必须通过以下方式进行:

// Serialize the JSON response for the access_token
public class AccessToken
{
    public string access_token { get; set; }
}

static async void GetCrmAccessToken(FormUrlEncodedContent content)
{
    try
    {
        // Send the x-www-form-urlencoded info to the OAuth2 end point
        HttpResponseMessage response = await Client.PostAsync("https://login.windows.net/42daf6bc-f7add741ac61/oauth2/token", content);
        // Get the body from the response
        var responseContent = await response.Content.ReadAsStringAsync();

        // Extract out the access token from the repsonse
        AccessToken responseBody = JsonConvert.DeserializeObject<AccessToken>(responseContent);

        if (responseBody.access_token != "")
        {
            // If there is an access token, take it and use it in
            // generating the query
            RequestCrmQuery(responseBody.access_token);
        }
        else
        {
            Console.WriteLine("Could not get the access token.");
        }

    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

基本上必须为我想从 JSON 中取出的键创建一个带有公共变量的类。

现在我有了访问令牌,查询的响应明显更大。

  1. 是否必须为要使用 JSON 响应的每个键创建一个公共变量? (有几十个)。
  2. 可以自动序列化吗?如果有,怎么做?
  3. 服务器响应中的某些键具有疯狂的名称,例如biz_status@OData.Community.Display.V1.FormattedValue。无法在 C# 中创建具有该名称的变量。这项工作将如何赋予我需要使用的重要关键之一?
  4. 我可以将变量称为其他名称,但在 JSON 中明确说明它对应的键吗?

【问题讨论】:

  • "为每个键创建一个方法"???检查您的主帐户是否搜索过有关从 JSON 自动创建类的信息。
  • 是的,不听你说的。
  • 请保留每个问题 1 且只有 1 个问题。否则答案将是:是的,是的,this 是的。

标签: c# json json.net


【解决方案1】:

我是否必须为要使用 JSON 响应的每个键创建一个公共变量? (有几十个)。 只定义你需要的。

这个我可以自动序列化吗?如果是这样,怎么做? 是的。请参阅此答案中的实现: Nested Lists and Automapper.Map

服务器响应中的某些键具有疯狂的名称,例如:biz_status@OData.Community.Display.V1.FormattedValue。无法在 C# 中创建具有该名称的变量。考虑到这是我需要使用的重要键之一,它如何工作?

创建如下属性:

[SuppressMessage("ReSharper", "InconsistentNaming")]
[SerializePropertyNamesAsCamelCase]
public class SearchResult
{
    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("abstract")]
    public string[] Abstract { get; set; }

    [JsonProperty("dateIssued")]
    public DateTime? DateIssued { get; set; }

    [JsonProperty("@search.score")]
    public decimal Score { get; set; }

    [JsonProperty("@search.highlights")]
    public Highlights Highlights { get; set; }
}

我可以将变量称为其他名称,但在 JSON 中明确说明它对应的键吗? 是的。见上面的实现

【讨论】:

    【解决方案2】:

    使用 json 的三种主要方式:

    1. 使用 json.net 的 JObject,您可以在其中获取属性,使用 JPath 访问特定节点(类似于 XPath)。好消息是您不需要创建类,但它的执行速度比序列化到对象要慢一些。

    2. 反序列化为 .net 对象。您需要为每个需要的属性创建结构。

    3. 反序列化为动态\expando 对象 - 这使您能够使用动态类型。也无需创建类。

    至于你的问题:

    1. 上面已回答。如果使用反序列化对象,则需要创建所有要访问的属性。

    2. 有些客户端在后台执行序列化。我更喜欢使用本机客户端并自己进行反序列化。您始终可以快速创建自定义内容。

    3. 您可以在任何属性上方使用[JsonProperty("&lt;name of json property")] 属性。

      [JsonProperty("realNodeName")] public string MyCoolProperty {get;set;}

    4. 同(3)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-25
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多