【发布时间】:2021-06-05 20:52:07
【问题描述】:
当我通过 Newtonsoft 序列化创建自定义类的 JSON 字符串时,我希望我的自定义类表现为(字符串)变量。
F.e.
public class YearMonth
{
public YearMonth(int year, int month) {
}
[JsonConstructor]
public YearMonth(string yearMonth) {
}
}
public class Data
{
public YearMonth startYearMonth { get; set; }
}
var data = new Data() { startYearMonth = new YearMonth(2021, 1) };
数据的 JSON 应该是:
{ startYearMonth = "202101" }
我应该如何意识到这一点?
我已经通过 [JsonConstructor] 属性进行了反序列化。
【问题讨论】:
-
您的 json 将
startYearMonth的值显示为字符串...而不是对象 -
请在您的问题中指定您使用的是哪个 json 序列化程序,例如:Newtonsoft、System.Text.Json 或其他。
-
@Jawad:我希望它在 JSON 字符串中
-
@PeterCsala:完成
标签: c# json class serialization deserialization