Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance from Jobject Newtonsoft

Inheritance from Jobject(Newtonsoft) the existents properties from class not serialized.

Why were the Id and Name properties not serialized?

public class Test : JObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var test = new Test();
        test["new_pro"] = 123456;
        test.Id = 1;
        test.Name = "Dog";


        var r = Newtonsoft.Json.JsonConvert.SerializeObject(test);

        // Result = { "new_pro":123456}

    }
}

Any idea?

like image 423
Gus Avatar asked Feb 13 '17 11:02

Gus


1 Answers

Whatever is the reason you want to do that - the reason is simple: JObject implements IDictionary and this case is treated in a special way by Json.NET. If your class implements IDictionary - Json.NET will not look at properties of your class but instead will look for keys and values in the dictionary. So to fix your case you can do this:

public class Test : JObject
{
    public int Id
    {
        get { return (int) this["id"]; }
        set { this["id"] = value; }
    }

    public string Name
    {
        get { return (string) this["name"]; }
        set { this["name"] = value; }
    }
}

If you just want to have both dynamic and static properties on your object - there is no need to inherit from JObject. Instead, use JsonExtensionData attribute:

public class Test {
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonExtensionData]
    public Dictionary<string, JToken> AdditionalProperties { get; set; } = new Dictionary<string, JToken>();
}

var test = new Test();
test.AdditionalProperties["new_pro"] = 123456;
test.Id = 1;
test.Name = "Dog";            
var r = Newtonsoft.Json.JsonConvert.SerializeObject(test);
like image 176
Evk Avatar answered Sep 20 '22 10:09

Evk