Parse json名称以C#中的数字开头,由Json.net - Newtonsoft提供

时间:2017-07-03 09:17:54

标签: c# json parsing json.net

我需要使用JSON.net(Newtonsoft)

在C#代码中解析JSON文件

但我收到的json文件就是这样开始的:

{ “3H”:3}

变量名以数字开头,但c#不能这样做。

如何以正确的方式设置值?我应该自己交换变量名吗?这会使代码非常脏。

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以通过映射来实现这一点:

class Program
{
    static void Main(string[] args)
    {
        string jsonInput = @"{""3h"":3}";
        var result = (myJsonObj)JsonConvert.DeserializeObject<myJsonObj>(jsonInput);
        Console.WriteLine(result.MyProperty);

    }
}

public class myJsonObj
{
    [JsonProperty(PropertyName = "3h")]
    public string MyProperty { get; set; }
}