如何将以NUMBER开头的JSON值转换为C#类



我使用的web服务的输出字段以数字开头,如下面的

[{"1_sell_count":"1","2_sell_count":"2","3_sell_count":"2"}]

由于我在C#中不能有一个以数字开头的变量,并且如果我更改属性名称,JsonConvert.DeserializeObject方法无法将JSON转换为我的类。

如何将此JSON输出转换为C#类?

List<myclass> reservationList = new List<myclass>();
using (var response = await httpClient.GetAsync(urlApi))
{
string apiResponse = await response.Content.ReadAsStringAsync();
reservationList = JsonConvert.DeserializeObject<List<myclass>>(apiResponse);
}

和myclass.cs

public class myclass
{
public string 1_sell_count{ get; set; }  //Not Valid Name
public string 2_sell_count{ get; set; }   //Not Valid Name
public string 3_sell_count{ get; set; }    //Not Valid Name
}

这个问题的解决办法是什么?

您可以将JsonProperty属性附加到属性上,如下所示,该属性指示JsonSerializer始终序列化具有指定名称的成员

public class myclass
{
[JsonProperty("1_sell_count")]
public string First_sell_count{ get; set; }  
[JsonProperty("2_sell_count")]
public string Second_sell_count{ get; set; }   

[JsonProperty("3_sell_count")]
public string Third_sell_count{ get; set; }    
}

看看小提琴-https://dotnetfiddle.net/xGhtxv

在以上情况下,您的转换逻辑将保持不变,即

reservationList = JsonConvert.DeserializeObject<List<myclass>>(apiResponse);

但是,您应该使用类中定义的属性名称来访问C#代码中的属性。

最新更新