MonoShiro
MonoShiro

Reputation: 83

JSON string contains null value

I have this line of code:

Message m = new Message(ciphertext, cipherKey, DateTime.Now, currentUser, serverUser);

currentUser and serverUser have been initialized as follows

serverUser = new User("Server", "svr", "Server", serverPublicKey);
currentUser = new User("Charlie", "c", "Charlie", publicKey);

m is then Serialized

string jsonMsg = JsonConvert.SerializeObject(m);

but the JSON string only shows the following

"{\"data\":\"ylPSml/wesmAqxP4DpZc7A==\",\"encryptedKey\":\"hlEX5u9eWeQb626ea4dq8D37jKyNkGGUMtdtrpKeaZxo5LfzRbCWvB9ZY5i3aL3RsG/XTf3vhLxPHztto/UJDVqGc+tQeGqUaVbgLJhCwmppmrEvciRrv3PRd/E8pCmmD69HVSN0/Vb0546AhPaI6OJqzhUpWRC+lcE7EEKNJT4=\",\"dateTime\":\"2016-01-07T19:18:08.315557+08:00\",\"dest\":null,\"src\":null}"

The fields for dest and src are both null. Am I doing this wrong or the SerializeObject function supposed to work this way?.

Edit

User and Message class:

public class User
{
    public string displayName { get; set; }
    public string id { get; set; }
    public string name { get; set; }
    public string publicKey { get; set; }

    public User(string displayName, string id, string name, string publicKey)
    {
        this.displayName = displayName;
        this.id = id;
        this.name = name;
        this.publicKey = publicKey;
    }
}


public class Message
{
    public string data { get; set; }
    public byte[] encryptedKey { get; set; }
    public DateTime dateTime { get; set; }
    public User dest { get; set; }
    public User src { get; set; }

    public Message(string data, byte[] encryptedKey, DateTime dateTime, User dest, User src)
    {
        this.dateTime = dateTime;
        this.data = data;
        this.encryptedKey = encryptedKey;
    }
}

Upvotes: 0

Views: 156

Answers (1)

Daniel Casserly
Daniel Casserly

Reputation: 3500

The Message constructor is missing the initalisation of the the two User based properties and should look like the following:

public Message(string data, byte[] encryptedKey, DateTime dateTime, User dest, User src)
{
    this.dateTime = dateTime;
    this.data = data;
    this.encryptedKey = encryptedKey;

    // Note these two lines:
    this.dest = dest;
    this.src = src;
}

Upvotes: 3

Related Questions