当在json中取消序列化时,并不是所有的属性都来自该文件



当我试图去序列化到抽象类列表时,Book类中的Genres属性保持为Null,而在Journal类中,它从我的json文件中获取值。

string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
using (FileStream streamFile = File.Open($"{folderPath}//products10.json", FileMode.OpenOrCreate))
{
using (StreamReader reader = new StreamReader(streamFile))
{
string fileContent = reader.ReadToEnd();
productsList = JsonConvert.DeserializeObject<List<ProductBase>>(fileContent,ProductBase.StrandartJsonConvert);
}
}

这是JSON文件:

[
{
"EditorName":"Me",
"Name":"DailyMail",
"IssueNumber":4,
"Genres":[1],
"Frequency":0,
"Id":"01c26581-3e3a-4bc2-bc97-dfbab0215f29",
"Description":"DailyMail",
"PublicationDate":"2022-01-19T12:44:32.57574+02:00",
"BasePrice":15.0,
"Type":"Journal"
},
{
"AuthorName":"Author",
"Title":"HarryPotter",
"Edition":3,
"Geners":[2,1],
"Synopsis":null,
"Id":"6674b82d-6d6d-49ac-9c92-7d84b0dd09b6",
"Description":"HarryPotter",
"PublicationDate":"2022-01-19T12:44:30.2413124+02:00",
"BasePrice":35.0,
"Type":"Book"
}
]

虽然在我的journal类中,一切都进入了,但在我的book类中——事实并非如此,看起来反序列化忽略了Genres属性。

public class Journal : ProductBase
{
public string EditorName { get; set; }
public string Name
{
get { return base.Description; }
set { base.Description = value; }
}
public int IssueNumber { get; set; }
public ICollection<JournalGenre> Genres { get; set; }
public JournalFrequency Frequency { get; set; }
public Journal(string editorName, string name, int issueNumber, DateTime publicationDate,
decimal basePrice, JournalFrequency frequency, params JournalGenre[] genres)
: base(name, publicationDate, basePrice)
{
this.EditorName = editorName;
this.IssueNumber = issueNumber;
this.Frequency = frequency;
this.Genres = genres.ToList();
}
}

这里所有的属性都得到了值。

public class Book : ProductBase
{
public string AuthorName { get; set; }
public string Title 
{ 
get { return base.Description; } 
set { base.Description = value; } 
}
public int Edition { get; set; }

public ICollection<BookGenre> Geners { get; set; }

public string Synopsis { get; set; }
public Book(string authorName, string title, DateTime publicationDate, decimal basePrice, int edition = 1, params BookGenre[] genres)
:base(title, publicationDate, basePrice)
{
this.AuthorName = authorName;
this.Edition = edition;
this.Geners = genres.ToList();
}
}

但这里的流派保持为null——const中的"流派"并没有从JSON文件中获得值——只有这个道具。任何其他东西都有价值。

不确定@JamesS为什么删除了他的答案,但他是对的-JSON文件中的属性是BookGeners,但构造函数参数是genres

将类和JSON文件中属性的拼写更正为Genres:

public class Book : ProductBase
{
...    
public ICollection<BookGenre> Genres { get; set; }
{
"AuthorName":"Author",
"Title":"HarryPotter",
"Edition":3,
"Genres":[2,1],
"Synopsis":null,
"Id":"6674b82d-6d6d-49ac-9c92-7d84b0dd09b6",
"Description":"HarryPotter",
"PublicationDate":"2022-01-19T12:44:30.2413124+02:00",
"BasePrice":35.0,
"Type":"Book"
}

或者更改构造函数参数的拼写以匹配JSON文件中使用的名称:

public Book(
string authorName, 
string title, 
DateTime publicationDate, 
decimal basePrice, 
int edition = 1, 
params BookGenre[] geners)

最新更新