【问题标题】:Send JSON via POST in C# and Use LINQ to access Objects在 C# 中通过 POST 发送 JSON 并使用 LINQ 访问对象
【发布时间】:2020-08-15 23:41:09
【问题描述】:

我希望在返回 JSON 时能够使用 LINQ 访问 JSON 对象。

我提到了Send JSON via POST in C# and Receive the JSON returned?Send and receive json via HttpClient

这是我目前所拥有的

 public static async Task<string> GetMailTip(string user)
        {
            var jsonData = new StringContent(FormatJson(CreateJsonGettingMailTip(user)), Encoding.UTF8, "application/json");
            var payload = await client.PostAsync($"https://graph.microsoft.com/v1.0/users/{user}/getMailTips", jsonData);
            string responseContent = "";

            if (payload.Content != null)
            {
                responseContent = await payload.Content.ReadAsStringAsync();

                Console.WriteLine(responseContent);
            }

            var getMailTip = responseContent["value"]
              .Children()
              .Where(i => i != null)
              .Select(c => c[""][""].Value<string>().Trim());

            return responseContent;
        }

返回的 JSON 是

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.mailTips)",
    "value": [
        {
            "emailAddress": {
                "name": "",
                "address": ""
            },
            "automaticReplies": {
                "message": "",
                "messageLanguage": {
                    "locale": "",
                    "displayName": ""
                },
                "scheduledStartTime": {
                    "dateTime": "",
                    "timeZone": ""
                },
                "scheduledEndTime": {
                    "dateTime": "",
                    "timeZone": ""
                }
            }
        }
    ]
}

我希望能够使用 LINQ 访问 JSON 中的 message 属性

任何帮助将不胜感激

【问题讨论】:

  • 不清楚你在问什么,或者你想做什么。
  • 你需要将responseContent反序列化为c#类对象。您可以使用jsonutils.com 为您拥有的 json 字符串创建 c# 类。
  • @MichaelRandall 请查看修改后的问题
  • 这能回答你的问题吗? Linq query JObject
  • 如果你想要一些快速的东西,那么没有比将 JSON 粘贴到 QuickType.io 之类的服务中更快的方法了,让它为你生成类和 json 反序列化代码,然后将其粘贴到你的项目中用一个衬里(他们也建议)将你的json变成类确实是要走的路。但是定义这样做比将Json粘贴到SO中并写一个Q更快;将这些东西作为适当的类与将查询转换为字符串词典等词典相比,编写查询会更容易、更快、更准确

标签: c# json linq json.net


【解决方案1】:

您转到http://quicktype.io(或类似的在线服务、jsonutils、json2csharp,或使用 Visual Studio 将 Json 粘贴为类功能 - 在所有执行此 QT 的站点中功能最全)将您的 json 转换为类.这使它更好地工作:

// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using SomeNamespaceHere;
//
//    var rootClassNameHere = RootClassNameHere.FromJson(jsonString);

namespace SomeNamespaceHere
{
    using System;
    using System.Collections.Generic;

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

    public partial class RootClassNameHere
    {
        [JsonProperty("@odata.context")]
        public Uri OdataContext { get; set; }

        [JsonProperty("value")]
        public Value[] Value { get; set; }
    }

    public partial class Value
    {
        [JsonProperty("emailAddress")]
        public EmailAddress EmailAddress { get; set; }

        [JsonProperty("automaticReplies")]
        public AutomaticReplies AutomaticReplies { get; set; }
    }

    public partial class AutomaticReplies
    {
        [JsonProperty("message")]
        public string Message { get; set; }

        [JsonProperty("messageLanguage")]
        public MessageLanguage MessageLanguage { get; set; }

        [JsonProperty("scheduledStartTime")]
        public ScheduledTime ScheduledStartTime { get; set; }

        [JsonProperty("scheduledEndTime")]
        public ScheduledTime ScheduledEndTime { get; set; }
    }

    public partial class MessageLanguage
    {
        [JsonProperty("locale")]
        public string Locale { get; set; }

        [JsonProperty("displayName")]
        public string DisplayName { get; set; }
    }

    public partial class ScheduledTime
    {
        [JsonProperty("dateTime")]
        public string DateTime { get; set; }

        [JsonProperty("timeZone")]
        public string TimeZone { get; set; }
    }

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

        [JsonProperty("address")]
        public string Address { get; set; }
    }

    public partial class RootClassNameHere
    {
        public static RootClassNameHere FromJson(string json) => JsonConvert.DeserializeObject<RootClassNameHere>(json, SomeNamespaceHere.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this RootClassNameHere self) => JsonConvert.SerializeObject(self, SomeNamespaceHere.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

(命名空间和类根的相关名称我选择了“SomeNamespaceHere”和“RootClassNameHere”;您可以选择不同的)

然后你像这样使用它(deser 步骤将根据你使用的服务而有所不同):

var rootClassNameHere = RootClassNameHere.FromJson(jsonString); //deser
var someLinq = rootClassNameHere.Value.Select(v => v.AutomaticReplies.Message); //query

【讨论】:

  • 感谢您的详细解答。我也会尝试这样做。
猜你喜欢
  • 2011-10-02
  • 2014-05-20
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
相关资源
最近更新 更多