我有以下类:
public class Goal : ObservableCollection<Activity>
{
public string Name { get; set; }
// constructors
public Goal() { }
public Goal(string name)
{
Name = name;
}
}
public class Activity
{
// properties
public string Name { get; set; }
public string Details { get; set; }
public bool FilterMe { get; set; }
// constructors
public Activity() { }
public Activity(string name)
{
Name = name;
}
}
当我将其写成JSON时,具有所有公共"活动"属性的"活动"列表将正确输出,但不包括"目标"的"名称"属性。我做错了什么?
// create a goal
Goal goal = new("Goal 1");
for (int a = 0; a < 5; a++)
{
Activity activity = new($"Activity {a + 1}");
if (a % 2 == 0) { activity.FilterMe = true; }
goal.Add(activity);
}
// write the output file
using FileStream fsWrite = File.Create("C:\Users\me\Desktop\Test.json");
JsonSerializer.Serialize<Goal>(new Utf8JsonWriter(fsWrite, new JsonWriterOptions() { Indented = true }), goal, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, IgnoreReadOnlyProperties = true });
以下是样本输出:
{
"Goal": [
{
"Name": "Activity 1",
"Details": "",
"FilterMe": true
},
{
"Name": "Activity 2",
"Details": "",
"FilterMe": false
},
{
"Name": "Activity 3",
"Details": "",
"FilterMe": true
},
{
"Name": "Activity 4",
"Details": "",
"FilterMe": false
},
{
"Name": "Activity 5",
"Details": "",
"FilterMe": true
}
]
}
正如您在上面的输出中看到的,缺少Goal的Name属性。它是一个公共属性,所以我认为序列化程序会获取它。
它永远不会以您想要的方式工作,这不是序列化程序的问题,而是C#创建对象的方式。即使您尝试使用文本编辑器手动创建json,它也将是无效的json。你将无法使用它。所以我唯一可以向你推荐的是,将你的课程改为这个
public class Goal
{
public ObservableCollection<Activity> Goals {get; set;} = new();
public string Name { get; set; }
public void Add (Activity activity)
{
Goals.Add(activity);
}
// constructors
public Goal() { }
public Goal(string name)
{
Name = name;
}
}
你所有的代码都能正常工作,没有任何问题
PS。
我非常有兴趣在序列化后看到你想要的json,请按照你想要的方式手动修复你发布的json并向我们展示。