这是我的JSON数据的样子,至少对于两条记录而言:
{"version":"1.0","players":{"timestamp":"1532153048","since":"Wed Dec 31 7:00:00 p.m. ET 1969","player":[{"draft_year":"2010","draft_round":"6","nfl_id":"antoniobrown/2508061","rotoworld_id":"5698","stats_id":"24171","position":"WR","stats_global_id":"406214","espn_id":"13934","kffl_id":"22341","weight":"181","id":"9988","birthdate":"584514000","draft_team":"PIT","name":"Brown, Antonio","draft_pick":"26","college":"Central Michigan","height":"70","jersey":"84","twitter_username":"AntonioBrown84","sportsdata_id":"16e33176-b73e-49b7-b0aa-c405b47a706e","team":"PIT","cbs_id":"1272852"},{"draft_year":"2018","draft_round":"1","rotoworld_id":"13048","status":"R","stats_id":"30972","position":"RB","stats_global_id":"883302","kffl_id":"37867","weight":"230","id":"13604","draft_team":"NYG","birthdate":"855291600","name":"Barkley, Saquon","draft_pick":"2","college":"Penn State","height":"71","jersey":"26","team":"NYG","cbs_id":"2185957"}]},"encoding":"utf-8"}
我想将其反序列化为一个列表,现在我只需要几个字段。这是我的模型:
public class MflPlayerJSON
{
[JsonProperty(PropertyName = "id")]
public string ID { get; set; }
[JsonProperty(PropertyName = "stats_id")]
public string YahooID { get; set; }
[JsonProperty(PropertyName = "draft_year")]
public string DraftYear { get; set; }
[JsonProperty(PropertyName = "team")]
public string Team { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
这是我的反序列化代码:从测试中我发现我没有正确地反序列化,但是我不知道该怎么做。我试图避免使用多个模型,但是如果需要,我会这样做:
var json = await response.Content.ReadAsStringAsync();
ViewBag.Msg2 = json.ToString();
var jObject = JObject.Parse(json);
// list = JsonConvert.DeserializeObject<MflPlayerJSON>(json);
var s = jObject.Count;
if (jObject.ContainsKey("players"))
{
ViewBag.Msg = s;
list = jObject["players"].ToObject<List<MflPlayerJSON>>();
}
错误消息是
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
我好亲近!请帮助
答案 0 :(得分:2)
这是您创建整个模型层次结构的替代解决方案。 我将json数据放入.json文件中,以避免所有引号转义
public class APIResult
{
[JsonProperty(PropertyName = "players")]
public PlayerData PlayerData {get; set;}
}
public class PlayerData
{
[JsonProperty(PropertyName = "player")]
public List<MflPlayerJSON> Players {get; set;}
}
public class MflPlayerJSON
{
[JsonProperty(PropertyName = "id")]
public string ID { get; set; }
[JsonProperty(PropertyName = "stats_id")]
public string YahooID { get; set; }
[JsonProperty(PropertyName = "draft_year")]
public string DraftYear { get; set; }
[JsonProperty(PropertyName = "team")]
public string Team { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("sample.json");
var o = JsonConvert.DeserializeObject<APIResult>(json);
}
}