【问题标题】:Use dash '-' in object property name in C# [duplicate]在 C# 中的对象属性名称中使用破折号“-”[重复]
【发布时间】:2018-12-27 14:15:06
【问题描述】:

在 C# 中,我将一个对象传递给一个函数。我需要在其中包含破折号“-”的对象中添加一个属性。如何在对象中传递这个虚线属性?

SendPushNotificationByAPNS(
device.RegisterId,
new
{
    aps = new
    {
        badge = 0
        alert = new
        {
            title = notificationTitle,
            body = notificationBody,
            sound = "default"
        },
        mutable-content = 1 <-- I need to add this but C# doesn't allow
    },
    entityId = entityId,
    entityType = entityType
});

【问题讨论】:

  • 这感觉像是 XY 问题 - meta.stackexchange.com/questions/66377/what-is-the-xy-problem 为什么需要在属性名称中使用 -
  • 如果您使用 JSON.Net,您可以定义自定义格式化程序。
  • 自定义格式化程序可能是矫枉过正。只需add an attribute 就很容易了。
  • @KevinAnderson 这对于诸如变量名称之类的标识符没有意义。您不传递变量的名称,而是传递它的值。

标签: c# json


【解决方案1】:

您不必以与 JSON 格式相同的方式在 C# 中命名属性,您必须创建一个包含 C# 命名约定所需的所有属性的类。

然后您可以添加[JsonProperty("mutable-content")] 属性以及您希望在 JSON 文件中看到的字段的名称。

在您的应用程序向另一个来源发出请求后,它将被自动序列化。

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2021-03-26
    相关资源
    最近更新 更多