我正在尝试将REST服务的响应反序列化为C#强类型类 - 但是我在这篇文章中遇到了同样的问题: How do I output this JSON value where the key starts with a number?
但是我有一个问题,你不能在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;
}
}
}
编辑:我无法改变服务推送数据的方式
答案 0 :(得分:0)
虽然在这种情况下没有直接构造强类型C#对象的方法,但您仍然可以手动解析json
字符串并提取值 -
var json = "{'1':{'name':'test','age':'test'}}";
var t = JObject.Parse(json)["1"];
Console.WriteLine(t["name"]); //test
Console.WriteLine(t["age"]); //test
答案 1 :(得分:0)
处理这个问题的正确方法是在目标类上使用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的评论回答