C# JSON 数据序列化并绑定到 DataGridView

C# JSON data serialized and binded to DataGridView

我有此数据 class 用于存储从 JSON 格式的网络数据解析的数据(使用 Json.NET 库):

[Serializable()]
public class MovieData
{
    public string FilePath { get; set; }
    public string OrigName { get; set; }

    [JsonProperty(PropertyName = "id")]
    public int Id { get; set; }

    [JsonProperty(PropertyName = "year")]
    public int Year { get; set; }

    [JsonProperty(PropertyName = "genres")]
    public string[] Genres { get; set; }
}

下一个 class 是为了能够序列化 MovieData 个对象的集合:

[Serializable()]
[XmlRoot("MovieCollection")]
public class MovieCollection
{
    [XmlArray("Movies")]
    [XmlArrayItem("Movie", typeof(Movie))]
    public List<Movie> movies = new List<MovieData>();
}

最后,我需要将 MovieData 的集合绑定到 DataGridView(或将单个 MovieData 对象绑定到 DataGridViewRow),例如:

dgvMovies.DataSource = movieCollection.movies;

是否可以不用之前DataGridViewColumn集合的硬设置来绑定呢?本机数据类型不是问题,问题是 string[] Genres 数组,我需要以某种方式将其格式化为 DataGridView,例如:

"genres[0] / genres[0] / ... genres[n]"

此时,当简单地设置DataSource为collectin时,这个数组被忽略了(无论如何都不显示)。

MovieDataclass中可以添加如下属性:

public string GenresAsString 
{ 
    get { return String.Join("/", Genres); }
    set { Genres = value.Split('/'); } 
}

如果您打算让用户修改此值,您肯定需要改进 setter 以使其更具弹性(修剪、删除空流派)。 否则你可以删除 setter.