6

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?

Gus
  • 856
  • 1
  • 8
  • 24

1 Answers1

14

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);
Evk
  • 98,527
  • 8
  • 141
  • 191
  • Hi this workaround is not a good idea for me. My class contains many properties (List, Nested Objects, etc) – Gus Feb 13 '17 at 15:35
  • 3
    Well then don't inherit from JObject or explain us why you absolutely must to do that, maybe we can find another workaround. – Evk Feb 13 '17 at 15:41
  • @Gus I've extended answer with one more option, probably that is what you need. – Evk Feb 13 '17 at 16:06
  • I decided look for this project. [https://github.com/RickStrahl/Expando]. Thanks for you help. I need to create dynamic properties for a class. – Gus Feb 13 '17 at 17:36
  • [JsonExtensionData] is perfect! I was also working on a misguided attempt to inherit from JObject. This solution works great for me. – tarrball Oct 08 '20 at 14:22