2016-11-24 28 views
0

我试图从REST服务反序列化到C#中强类型类 - 但是我遇到了同样的问题在这篇文章中有: How do I output this JSON value where the key starts with a number?解析JSON响应,其中对象以c中的数字开头#

但是我有这个问题,你不能在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

发布样品JSON。 –

+2

我认为这将有助于http://stackoverflow.com/questions/24218536/deserialize-json-that-has-some-property-name-starting-with-a-number – HebeleHododo

+0

@HebeleHododo非常感谢你! –

回答

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的评论答案

+0

你如何为'[{'1':{'name':'test','age':'test'}},{'2':{'name':'another','age ':'another'}}]' –

+0

@AmitKumarGhosh你会在属性名称中加入“1”,或者如果它的可变数量的项目,你会使用for循环使用你的方法。 –

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 
+0

感谢您的回复 - 这是我要如何处理它,直到我看到:http://stackoverflow.com/questions/24218536/deserialize-json-that-has-some-物业名称开始与一个数字,这使得它成为可能。 –