2014-07-26 39 views
0

我試圖填充這個類的屬性:Json.net不填充類屬性C#

public class Summoner 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
    public int profileIconId { get; set; } 
    public int summonerLevel { get; set; } 
    public long revisionDate { get; set; } 
} 

有了這個JSON:

{"SummonerName":{"id":445312515,"name":"SummonerName","profileIconId":28,"summonerLevel":30,"revisionDate":140642312000}} 

使用JSON.net有以下幾點:

public static Summoner getRecentGames(string summonerId) 
    { 
     Summoner summoner = new Summoner(); 
     try 
     { 
      using (var webClient = new System.Net.WebClient()) 
      { 
       var json = webClient.DownloadString("https://eu.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/"+summonerId+"?api_key="+api_key); 
       webClient.Dispose(); 
       summoner = JsonConvert.DeserializeObject<Summoner>(json); 
       return summoner; 
      } 
     } 
     catch(Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 
     return null; 
    } 

該屬性從來沒有指定的值,是它與他們作爲一個外部對象在JSON whe我需要的值是在內部對象內嗎?

我是一個新的程序員,所以很抱歉,如果這是一個愚蠢的錯誤,謝謝。

回答

3

您需要爲您的JSON包含SummonerName特性的包裝:

public class Wrapper 
{ 
    public Summoner SummonerName { get; set; } 
} 

,你要去反序列化JSON到:

public static Summoner getRecentGames(string summonerId) 
{ 
    try 
    { 
     using (var webClient = new System.Net.WebClient()) 
     { 
      var json = webClient.DownloadString("https://eu.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/"+summonerId+"?api_key="+api_key); 
      var wrapper = JsonConvert.DeserializeObject<Wrapper>(json); 
      return wrapper.SummonerName; 
     } 
    } 
    catch(Exception e) 
    { 
     Console.WriteLine(e.ToString()); 
    } 
    return null; 
} 

還注意到自己的webClient實例包裹在一個using指令 - 手動調用.Dispose()方法完全沒有意義 - 這就是using聲明的全部目的。


UPDATE:

看來,SummonerName財產在你的JSON是動態的(這是一個API,但反正很糟糕的設計),並意味着你不能使用強類型包裝。

這裏是你能怎麼處理這個問題:

using (var webClient = new System.Net.WebClient()) 
{ 
    var json = webClient.DownloadString("https://eu.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/"+summonerId+"?api_key="+api_key); 
    var summoner = JObject.Parse(json).Values().First().ToObject<Summoner>(); 
    return summoner; 
} 
+0

感謝達林,我已經相應地更新它。我現在遇到的問題是,只要我嘗試輸出返回的召喚師的名稱屬性,就會拋出一個NullReferenceException異常。我不確定爲什麼發生這種情況,該方法不返回空值。 –

+0

如果'getRecentGames'方法返回一個非空的'Summoner'實例,那麼在這個實例上調用'.name'將不會產生NullReferenceException。哪些屬性爲空?你確定你的'getRecentGames'方法不會拋出異常並返回null嗎?嘗試調試您的代碼,並檢查從遠程端點讀取的'json'字符串變量的值以及反序列化的'Wrapper'實例的屬性。 –

+0

看起來正在返回的Summoner實例爲null,是否發生這種情況,因爲JSON中的包裝對象的名稱根據正在搜索的召喚者ID而變化?我在這裏給你一個例子:https://gist.github.com/Coppercrawler/d0e86ff8ce2244a3fc17 - 再次感謝所有這些幫助,我真的很感激它。 –