反序列化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; }
}
获取各种电影的空引用。
答案 0 :(得分:0)
我从您提供的URL中获得了JSON
的例子。
这将是您的C#实体以捕获JSON:
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();
}
然后可以确定它不为空。