2017-09-16 114 views
0

根據此討論中的代碼(How to build object hierarchy for serialization with json.net?),我將如何初始化JNotification並將值分配給包含JPayload,JCustomData,JFilter的JNotification?C#初始化類並分配值Newtonsoft.Json

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; } 
} 

回答

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#的默認命名約定,您可以將序列化程序設置爲小寫每個屬性的第一個字母。

也有屬性配置輸出(如果你想跳過一個屬性,使用枚舉的字符串,等等)

+0

特勒爾斯,正是我一直在尋找。謝謝! – Jeffry

0

我很確定json反序列化會調用no-arg公共構造函數。如果你在JNotification的構造函數中構造這些對象,它們應該被初始化。