billybob
billybob

Reputation: 2998

Newtonsoft json converter - Cannot serialize an all attributes of an overridden class

I wrote a little example that explains my problem.

I have main class: MainClass

public class MainClass
{
    public string ID
    {
        get;
        set;
    }
}

And I have leaf class: LeafClass

public class LeafClass : MainClass
{
    public string ID2
    {
        get;
        set;
    }

    #region Constructor
    public LeafClass(MainClass oMainClass)
    {
        this.ID = oMainClass.ID;
        this.ID2 = "my 2nd ID";
    }
    #endregion
}

In my main:

MainClass MC = new MainClass();
LeafClass[] LF = {new LeafClass(MC), new LeafClass(MC)};
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
serializer.Converters.Add(new Newtonsoft.Json.Converters.KeyValuePairConverter());
string JsonData = JsonConvert.SerializeObject(LF, serializer.Converters.ToArray());

I don't have my ID2 in my Json, I have only the base attributes. Any idea how to make it work?

Upvotes: 0

Views: 739

Answers (2)

billybob
billybob

Reputation: 2998

I found out how to solve my problem.

I had to add this decorator on the LeafClass [JsonObject(MemberSerialization.OptIn)] and [JsonProperty]on each property.

[JsonObject(MemberSerialization.OptIn)]
public class LeafClass : MainClass
{
    [JsonProperty]
    public string ID2
    {
        get;
        set;
    }

    #region Constructor
    public LeafClass(MainClass oMainClass)
    {
        this.ID = oMainClass.ID;
        this.ID2 = "my 2nd ID";
    }
    #endregion
}

Upvotes: 1

Scottie
Scottie

Reputation: 11308

Try this:

[Serializable]
public class MainClass
...

[Serializable]
public class LeafClass : MainClass
...

Edited...

You are passing in an instance of MainClass that has never set ID, yet you are assigning ID to that value. ID is null.

public LeafClass(MainClass oMainClass)
{
    this.ID = oMainClass.ID;  // <-- oMainClass.ID is null because you never set it in oMainClass
    this.ID2 = "my 2nd ID";
}

try this:

MainClass MC = new MainClass();
MC.ID = "ABC";
LeafClass[] LF = { new LeafClass(MC), new LeafClass(MC) };

Upvotes: 0

Related Questions