c# - 如何创建多层次的 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 对象?谢谢你。
解决方案
正如@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 字段名称如何。希望能帮助到你。
推荐阅读
- python - 系列不匹配(在“不匹配”系列中查找值)
- git - JetBrains Upsource 在连接 GCP 云源存储库 URL 时抛出未知主机错误 | SSH 连接
- javascript - 是否可以使用 JS 获取代码正在执行的函数的名称?
- javascript - 使用 React 我正在尝试生成代表三个集合的三个按钮,单击时会将您带到该卡片集合
- python-3.x - 我可以获取“外部”类属性并在“内部”类中使用它们吗?
- css - 如何在css中使用渐变的半圆边框
- java - android获取会话ID
- r - 如何创建带有 dbf 扩展名的文件列表?
- angular - 生产构建中的错误:索引 html 生成失败
- html - 如何让我的网站用户更改字体颜色而不让他们访问代码?