【问题标题】:Creating a JSON string, if the left-hand varaible has dashes in如果左侧变量中有破折号,则创建 JSON 字符串
【发布时间】:2017-05-21 03:08:54
【问题描述】:

我正在尝试创建一个 json 字符串以通过 httprequest 发送,我有这样的 json 字符串:

{
    "a-string": "123",
    "another-string": "hello",
    "another": "1"
}

我的问题是,如果我尝试像这样生成它

 string json = new JavaScriptSerializer().Serialize(new
    {
    "a-string" = "123",
    "another-string" = "hello",
    "another" = "1"
    });

导致:

那么有什么方法可以尝试执行上述操作而不会出现该错误?

【问题讨论】:

标签: c#


【解决方案1】:

使用Json NewtonSoft NuGet 包。然后使用我的答案here 为您的 json 创建一个 C# 类。由于您的 json 包含在 C# 中不允许作为属性名称的名称,因此您可以使用 JsonPropety 属性,以便它可以在序列化期间使用它。以下是全部代码:

public class Rootobject
{
    [JsonProperty("a-string")]
    public string astring { get; set; }

    [JsonProperty("another-string")]
    public string anotherstring { get; set; }
    public string another { get; set; }
}

public class Program
{
    public static void Main()
    {
        var root = new Rootobject { another = "1", anotherstring = "hello", astring = "123" };
        string json = JsonConvert.SerializeObject(root);

        Console.Read();
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2010-10-02
    • 2012-08-23
    • 1970-01-01
    相关资源
    最近更新 更多