反序列化 json 字符串时,是否需要为字符串的每个部分设置一个属性,或者为什么字符串没有转换?
var webClient = new WebClient();
var json = webClient.DownloadString("https://omdb-api.now.sh/?i=tt7784604");
var movies = JsonConvert.DeserializeObject<JsonMovies>(json);
return View(movies);
public class JsonMovies
{
public IList<MovieData> movies { get; set; }
}
public class MovieData
{
public string Title { get; set; }
}
获取 var 电影的空引用。
我从您提供的 URL 中得到了JSON
示例。
这将是用于捕获 JSON 的 C# 实体:
public class Rating
{
public string Source { get; set; }
public string Value { get; set; }
}
public class RootObject
{
public string Title { get; set; }
public string Year { get; set; }
public string Rated { get; set; }
public string Released { get; set; }
public string Runtime { get; set; }
public string Genre { get; set; }
public string Director { get; set; }
public string Writer { get; set; }
public string Actors { get; set; }
public string Plot { get; set; }
public string Language { get; set; }
public string Country { get; set; }
public string Awards { get; set; }
public string Poster { get; set; }
public List<Rating> Ratings { get; set; }
public string Metascore { get; set; }
public string imdbRating { get; set; }
public string imdbVotes { get; set; }
public string imdbID { get; set; }
public string Type { get; set; }
public string DVD { get; set; }
public string BoxOffice { get; set; }
public string Production { get; set; }
public string Website { get; set; }
public string Response { get; set; }
}
您要做的是基于此模型对其进行反序列化。
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://omdb-api.now.sh/?i=tt7784604");
if (!string.IsNullOrEmpty(json))
{
var movies = JsonConvert.DeserializeObject<RootObject>(json);
return View(movies);
}
//Json is null returns null to your view.
return View();
}
然后你可以确定它不是空的。