基于此讨论中的代码(How to build object hierarchy for serialization with json.net?),如何初始化JNotification并将值赋给包含JPayload,JCustomData,JFilter的JNotification?
public class JNotification
{
public string status { get; set; }
public JPayload payload = new JPayload();
public JFilter filter = new JFilter();
}
public class JPayload
{
public string title { get; set; }
public string message { get; set; }
public JCustomData customData = new JCustomData();
}
public class JCustomData
{
public string addType { get; set; }
public string addTitle { get; set; }
public string addMessage { get; set; }
public int addAppraiserId { get; set; }
public int addAppraisalId { get; set; }
public int addAppraisalCommentId { get; set; }
public int addAppraisalStatusHistoryId { get; set; }
}
public class JFilter
{
public int AppraiserId { get; set; }
}
答案 0 :(得分:1)
要创建对象图,序列化为json并反序列化,请执行:
var data = new JNotification() {
status = "New",
payload = new JPayload() {
title = "SomeTitle",
message = "msg",
customData = new JCustomData() { ... }
},
filter = new JFilter() {
AppraiserId = 1
}
}
string json = JsonConvert.SerializeObject(data);
JNotification dataAgain = JsonConvert.DeserializeObject<JNotification>(json);
上面使用Newtonsoft.Json
NuGet包。
请注意,如果要使用C#的默认命名约定,可以将序列化程序设置为小写每个属性的第一个字母。
还有用于配置输出的属性(如果要跳过属性,请使用字符串作为枚举等)。
答案 1 :(得分:0)
我非常确定json反序列化会调用no-arg公共构造函数。如果在JNotification的构造函数中构造这些对象,则应初始化它们。