1

Based on this code in this discussion (How to build object hierarchy for serialization with json.net?), how would I initialize the JNotification and assign values to to JNotification which contains 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; }
}
Jeffry
  • 13
  • 4

2 Answers2

3

To create the object graph, serialize to json and deserialize, do:

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

Above using the Newtonsoft.Json NuGet package.

Please note that if you want to use the default naming convention of C#, you can set the serializer up to lowercase the first letter of each property.

There are also attributes to configure the output (if you want to skip a property, use strings for enums, etc.)

Troels Larsen
  • 4,462
  • 2
  • 34
  • 54
0

I'm pretty sure json deserialization will call the no-arg public constructor. If you construct those objects in the constructor of the JNotification, they should be initialized.

Stephen Vernyi
  • 768
  • 5
  • 11