Joshua Frank
Joshua Frank

Reputation: 13828

Custom JSON serialization/deserialization to read property in multiple possible formats

My application reads JSON files created using a format like this:

{
  "myProperty": {complex JSON here}
}
class MyClass
{
   public MyChildClass MyProperty {get; set;}
}

I need to change the way the class works, so that it looks like this instead:

class MyClass
{
   public MyNewChildClass MyNewProperty {get; set;}
}

and I need to be able to support files created in the older format, but also support a file if it was created using the new format.

I have the code to convert a MyChildClass object into a MyNewChildClass object, but how can I set up the serialization so that the object can deserialize the old format, changing the property name and type from MyChildClass MyProperty to MyNewChildClass MyNewProperty AND just use the new format when serializing AND deserialize using the new format if that is what the JSON file contains?

Upvotes: 3

Views: 78

Answers (2)

Johnathan Barclay
Johnathan Barclay

Reputation: 20354

Why not add a private property to your class that will set your new property:

class MyClass
{
   [JsonProperty]
   private MyChildClass MyProperty { set => MyNewProperty = YourConversionMethod(value); }

   public MyNewChildClass MyNewProperty { get; set; }
}

The JsonProperty attribute will ensure that the private setter is used.

Upvotes: 1

Jawad
Jawad

Reputation: 11364

If you use both properties, the json will work for both, new and old.

class MyClass
{
   [JsonPropert("myProperty")]
   public MyChildClass MyProperty {get; set;}

   [JsonProperty("myNewProperty")] // -> Remember, case matters.
   public MyNewChildClass MyNewProperty {get; set;}
}

When you deserialize the class, add a check to see which is not null and work with that (different methods for each i guess). This should help you keep the breaking change to a minimum.

BTW>. if you have the code that converts the new to the old or vice versa, you can check if the value of old is null, then run that process/method you have to convert new to old and continue on with the object. Remember, it would have to be After the deserialization,

var properties = JsonConvert.DeserializeObject<MyClass>("data");
if (properties.MyNewProperty == null) 
{
   properties = myMethodToConvertOldToNew(properties);
}

public MyClass myMethodToConvertOldToNew(MyClass)
{
  if (properties.New == null)
  {
     properties.New = ConversionMethod(properties.Old, properties.New);
     // dont have to, but,
     properties.Old = null;
  }
  return properties.

}

Upvotes: 2

Related Questions