如何将以数字开头的 JSON 值转换为 C# Class
How to convert JSON values that START with a NUMBER to C# Class
我使用的网络服务的输出字段以如下数字开头
[{"1_sell_count":"1","2_sell_count":"2","3_sell_count":"2"}]
因为我不能在 C# 中有一个以数字开头的变量,如果我更改 属性 名称,JsonConvert.DeserializeObject 方法无法进行转换 JSON 到我的 Class.
如何将此 JSON 输出转换为 C# class?
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; }
}
查看 fiddle - https://dotnetfiddle.net/xGhtxv
有了上面的内容,您的转换逻辑将保持不变,即
reservationList = JsonConvert.DeserializeObject<List<myclass>>(apiResponse);
但是,您应该使用 class 中定义的 属性 名称来访问 C# 代码中的 属性。
我使用的网络服务的输出字段以如下数字开头
[{"1_sell_count":"1","2_sell_count":"2","3_sell_count":"2"}]
因为我不能在 C# 中有一个以数字开头的变量,如果我更改 属性 名称,JsonConvert.DeserializeObject 方法无法进行转换 JSON 到我的 Class.
如何将此 JSON 输出转换为 C# class?
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; }
}
查看 fiddle - https://dotnetfiddle.net/xGhtxv
有了上面的内容,您的转换逻辑将保持不变,即
reservationList = JsonConvert.DeserializeObject<List<myclass>>(apiResponse);
但是,您应该使用 class 中定义的 属性 名称来访问 C# 代码中的 属性。