如果左侧变量有破折号,则创建一个JSON字符串

时间:2017-05-20 18:55:23

标签: c#

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

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

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

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

导致:enter image description here

那么在没有出现错误的情况下尝试执行上述操作的方法是什么?

1 个答案:

答案 0 :(得分:0)

使用Json NewtonSoft NuGet包。然后使用我的答案here为你创建一个C#类json。由于您的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();
    }
}