Ваш Response
класс немного ошибочен. Он не соответствует JSON, который вы опубликовали.
public List<TriviaQuestion> Questions { get; set; }
должно быть:
public List<TriviaQuestion> Results { get; set; }
Кроме того, поскольку ваш JSON имеет корпус со змеей, для захвата response_code
, correct_answer
иincorrect_answers
значений, которые вам понадобятся для украшения свойств вашего класса JsonProperty
атрибутами, т.е. [JsonProperty(PropertyName = "incorrect_answers")]
, или вы можете использовать ContractResolver:
var contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
var response = JsonConvert.DeserializeObject<Response>(json, new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Таким образом, ваши полные классы будут:
public class TriviaQuestion
{
public string Category { get; set; }
public string Type { get; set; }
public string Difficulty { get; set; }
public string Question { get; set; }
// only need this if not using the ContractResolver
[JsonProperty(PropertyName = "correct_answer")]
public string CorrectAnswer { get; set; }
// only need this if not using the ContractResolver
[JsonProperty(PropertyName = "incorrect_answers")]
public List<string> IncorrectAnswers { get; set; }
}
public class Response
{
// only need this if not using the ContractResolver
[JsonProperty(PropertyName = "response_code")]
public int ResponseCode { get; set; }
public List<TriviaQuestion> Results { get; set; }
}
Тогда вы сможете десериализовать:
var json = "{\r\n \"response_code\":0,\r\n \"results\": [\r\n { \r\n \"category\":\"Entertainment: Video Games\",\r\n \"type\":\"multiple\",\r\n \"difficulty\":\"medium\",\r\n \"question\":\"In Need for Speed: Underground, what car does Eddie drive?\",\r\n \"correct_answer\":\"Nissan Skyline GT-R (R34)\",\r\n \"incorrect_answers\": [\r\n \"Mazda RX-7 FD3S\",\r\n \"Acura Integra Type R\",\r\n \"Subaru Impreza 2.5 RS\"\r\n ]\r\n }]\r\n}";
// if using JsonProperty attributes
var response = JsonConvert.DeserializeObject<Response>(json);
// or
// if using ContractResolver
var contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
var response = JsonConvert.DeserializeObject<Response>(json, new JsonSerializerSettings
{
ContractResolver = contractResolver
});