首页 > 解决方案 > 如何创建多层次的 JSON 对象?

问题描述

我想使用 api 发送邮件: https ://docs.microsoft.com/en-US/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations#SendMessageOnTheFly

 *POST https://outlook.office.com/api/v2.0/me/sendmail*

{
  "Message": {
    "Subject": "Meet for lunch?",
    "Body": {
      "ContentType": "Text",
      "Content": "The new cafeteria is open."
    },
    "ToRecipients": [
      {
        "EmailAddress": {
          "Address": "garthf@a830edad9050849NDA1.onmicrosoft.com"
        }
      }
    ],
    "Attachments": [
      {
        "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
        "Name": "menu.txt",
        "ContentBytes": "bWFjIGFuZCBjaGVlc2UgdG9kYXk="
      }
    ]
  },
  "SaveToSentItems": "false"
}

我尝试通过以下方式创建 Message Json:

 var json=new {  "Message": { "Subject": "Meet for lunch?",.......,"SaveToSentItems": "false"};

但 C# 不允许。

如何Message在 C# 中创建 Json 对象?谢谢你。

标签: c#json

解决方案


正如@ataboo建议的那样,最好的方法是创建多个匹配 json 结构的类并将对象序列化为 JSON。

除了Attachment类之外,创建所有其他类应该很简单。C# 不允许将属性命名为“ public string @odata.type { get; set; }

NewtonSoft.Json 有一个解决这个问题的方法。为具有 JsonProperty 属性的字段创建具有任何合法属性名称的类,如下所示

public class Attachment
{
    [JsonProperty("@odata.type")]
    public string OdataType { get; set; }

    public string Name { get; set; }

    public string ContentBytes { get; set; }
}

JsonProperty 属性允许您根据需要命名属性,而不管 json 字段名称如何。希望能帮助到你。


推荐阅读