c# JSON SerializeObject与自定义列表

本文关键字:自定义 列表 SerializeObject JSON | 更新日期: 2023-09-27 18:18:41

我有一个JSON对象,像这样:

    public class RootObject
{
    public string Number { get; set; }
    public string ChannelType { get; set; }
    public string ServiceName { get; set; }
    public List<ImageInfos> ImageInfos { get; set; }
    public bool IsInMixedFolder { get; set; }
    public string Name { get; set; }
    public string Id { get; set; }
    public string DateCreated { get; set; }
    public string DateModified { get; set; }
    public string DateLastSaved { get; set; }
    public List<object> LockedFields { get; set; }
    public string ParentId { get; set; }
    public List<string> Studios { get; set; }
    public List<string> Genres { get; set; }
    public ProviderIds ProviderIds { get; set; }
}

与imageinfo像这样:

    public class ImageInfos
{
    private string Path;
    private string Type;
    private string DateModified;
    public ImageInfos(string Path, string Type, string DateModified)
    {
        this.Path = Path;
        this.Type = Type;
        this.DateModified = DateModified;
    }

我正试图用值填充json imageinfo - list并将其序列化为一个新字符串:

            jsonObject = JsonConvert.DeserializeObject<RootObject>(json);
            List<ImageInfos> newInfos = new List<ImageInfos>();
            newInfos.Add(new ImageInfos("Test", "Test", "Test"));
            jsonObject.ImageInfos = newInfos;
            string newJSON = JsonConvert.SerializeObject(jsonObject);

但是新的json看起来是这样的:

"{'"'":'"35 '",'"ChannelType '",'"电视'",'"名'",'"DVBLink '",'"imageinfo '":[{}],'" IsInMixedFolder '":假的,'"'",'"13街高清' '",'"Id":'"466 ab1fb9be4f77e65ad2b229a15c326 '",'"DateCreated '",'"2015 - 09 - 14 t12:55:51.4081476z '",'"DateModified '",'"0001 - 01 - 01 t00:00:00.0000000z '",'"DateLastSaved '",'"2015 - 10 - 17 t13:34:37.4214116z '",'"LockedFields ' ":[], '"ParentId '":'"00000000000000000000000000000000 '",'"工作室' ":[],'"流派' ":[],'"ProviderIds '":{'"ProviderExternalId '",'"13250000 '"}}"

为什么imageinfo在新的JSON字符串中是空的?

c# JSON SerializeObject与自定义列表

ImageInfos的所有属性都是private。Json。NET默认情况下不会序列化它们,因此结果JSON显示一个空对象。

强制Json。. NET序列化私有属性,为每个属性添加[JsonProperty]属性:

public class ImageInfos
{
    [JsonProperty]
    private string Path;
    [JsonProperty]
    private string Type;
    [JsonProperty]
    private string DateModified;
    public ImageInfos(string Path, string Type, string DateModified)
    {
        this.Path = Path;
        this.Type = Type;
        this.DateModified = DateModified;
    }
}