我正在尝试将 REST 服务的响应反序列化为 C# 强类型类 - 但是我遇到了本文中的相同问题:如何输出键以数字开头的 JSON 值?
但是我有一个问题,你不能在 C# 中以数字开头变量名 - 这意味着该级别的类只会反序列化为 null。
我需要知道如何进入对象并将它们反序列化到 C# 类中。
我当前的代码如下:
public static async Task<T> MakeAPIGetRequest<T>(string uri)
{
Uri requestURI = new Uri(uri);
using (HttpClient client = new HttpClient())
{
HttpResponseMessage responseGet = await client.GetAsync(requestURI);
if (responseGet.StatusCode != HttpStatusCode.OK)
{
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
responseGet.StatusCode,
responseGet.Content));
}
else
{
string response = await responseGet.Content.ReadAsStringAsync();
T objects = (JsonConvert.DeserializeObject<T>(response));
return objects;
}
}
}
编辑:我无法更改服务将数据推回的方式
处理这个问题的正确方法是在目标类上使用 JsonProperty 标签来定义要监听的 Json 属性,如下所示(引用自https://stackoverflow.com/questions/24218536/deserialize-json-that-has-some-property-name-starting-with-a-number
public class MyClass
{
[JsonProperty(PropertyName = "24hhigh")]
public string Highest { get; set; }
...
感谢@HebeleHododo 的评论回答
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)