3

I am trying to serialize Item object but the ActionItem object would be always changing.

C# Object

public class Item
{
    public string Name { get; set; }
    public ActionItem Action { get; set; }
}

public class ActionItem
{
    public string Value { get; set; }
}

When I serialize the object above I will be getting:

{
   Name: null,
   Action: {
      Value: null
   }
}

But I am expecting it as { Name: null , Action: {} }

I would like to refactor the ActionItem object so that it can take other format of json/schema.
E.g.

{
    Name : 'MyName',
    Action : 
         {
           ActName: 'Finish',
           ActType: 1
           //...might differ because this field is always changing
         }
}

I tried serializing, using JsonConvert.Serialize(), a new Object() and it is serialized as {} but I cant assign ActionItem object as a new Object()

How can I achieve my desired result for this?

UPDATE
I made it work somehow after watching this snippet. I just changed the ActionItem to ExpandoObject.

Hexxed
  • 683
  • 1
  • 10
  • 28
  • Do you mean that you don't want to serialize nulls? – ProgrammingLlama Nov 14 '18 at 05:21
  • Possible duplicate of [How to ignore a property in class if null, using json.net](https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net) – ProgrammingLlama Nov 14 '18 at 05:22
  • 1
    Not sure if I understood the question correctly. I am assuming you are serializing a `new Item()`. Since, instance of class `Item` is initialized, it is returning the expected result that you are getting. Now, note that, instantiating a new instance of `Item` class *does not* instantiated a new object of type `ActionItem`. That's why you are getting `Action: { Value: null }`. – vpv Nov 14 '18 at 05:45
  • @V.P.Verma I want to serialize the `Item` object however serializing `ActionItem` field is different. The task is that `ActionItem` is not just `Value` can be other property as well. – Hexxed Nov 14 '18 at 06:26

0 Answers0