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我需要的值是在內部對象內嗎?
我是一個新的程序員,所以很抱歉,如果這是一個愚蠢的錯誤,謝謝。
感謝達林,我已經相應地更新它。我現在遇到的問題是,只要我嘗試輸出返回的召喚師的名稱屬性,就會拋出一個NullReferenceException異常。我不確定爲什麼發生這種情況,該方法不返回空值。 –
如果'getRecentGames'方法返回一個非空的'Summoner'實例,那麼在這個實例上調用'.name'將不會產生NullReferenceException。哪些屬性爲空?你確定你的'getRecentGames'方法不會拋出異常並返回null嗎?嘗試調試您的代碼,並檢查從遠程端點讀取的'json'字符串變量的值以及反序列化的'Wrapper'實例的屬性。 –
看起來正在返回的Summoner實例爲null,是否發生這種情況,因爲JSON中的包裝對象的名稱根據正在搜索的召喚者ID而變化?我在這裏給你一個例子:https://gist.github.com/Coppercrawler/d0e86ff8ce2244a3fc17 - 再次感謝所有這些幫助,我真的很感激它。 –