0

We have two classes from legacy, which we are making changes.

Just created some sample class to demonstrate the scenario.

If we assign values and convert to json we are getting only the below missing the Reason field.

When we debug we can see that this reason is missing.

Since its a legacy code which is used inn lots of places, we are trying to keep the same structure of the class if there is any work around.

[{"Name":"foo1"},{"Name":"foo2"}]

enter image description here

        var foo = new Foo { Name = "foo1" };
        var foo2 = new Foo { Name = "foo2" };
        var foos = new List<Foo> { foo, foo2 };
        var fooList = new FooList();
        fooList.Reason = "Strange";
        fooList.AddRange(foos);
        var jsonFoo = JsonConvert.SerializeObject(fooList);

 public class Foo
{
    public string  Name { get; set; }
}
 
public class FooList:List<Foo>
{
    public string  Reason { get; set; }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
ezycoder
  • 103
  • 2
  • 9

1 Answers1

0

This works:

public class FooList
{
    public List<Foo> Foos;
    public string Reason { get; set; }
}

var foo = new Foo { Name = "foo1" };
var foo2 = new Foo { Name = "foo2" };
var foos = new List<Foo> { foo, foo2 };
var fooList = new FooList();
fooList.Reason = "Strange";
fooList.Foos = foos;
var jsonFoo = JsonConvert.SerializeObject(fooList);

It gives:

{"Foos":[{"Name":"foo1"},{"Name":"foo2"}],"Reason":"Strange"}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172