)
基于此讨论中的此代码(如何构建与json.net序列化的对象层次结构?),我如何初始化jnotification并将值分配给jnotification,其中包含jpayload,jcustomdata,,jfilter?
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; }
}
创建对象图,序列化与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#的默认命名约定,则可以将序列化器设置为小写,以较低为每个属性的第一个字母。
也有配置输出的属性(如果要跳过属性,将字符串用于枚举等)
我敢肯定,json挑战将称为no-arg public构造师。如果您在jnotification的构造函数中构造这些对象,则应初始化它们。