0

I have the following class:

public class PropoertyValue {
 string Id {get;set;}
 object Value {get;set;}
 string Type {get;set;}

}

When I serialize/deserialize Json I want the value property reflects the type specified in "Type" property. How can I do this?

Here Sample: Json: {"Id":"Property1","Value":0,"Type":"System.Int32"} // The Type must by any POCO object type.

When Deserialized I would call a PropertyValue class method that return the value:

public getValue<T>() => (T)Value;

Can anyone help me with serialization/deserialization of the PropertyValue type?

Matteo Fioroni
  • 103
  • 2
  • 4
  • 1
    You can refer to [Support polymorphic deserialization](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#support-polymorphic-deserialization) article and write your own converter to handle the `Type` property. Answers from this [question](https://stackoverflow.com/q/58074304/4728685) also may be helpful – Pavel Anikhouski Oct 29 '20 at 10:54

1 Answers1

2

When your JSON deserializes to class, object property converts to the JsonElement.with this Extension Method, you can convert your JsonElement to every type you want.

public static T ToObject<T>(this JsonElement element)
{
  if (element.ValueKind != JsonValueKind.Null)
      return JsonSerializer.Deserialize<T>(element.GetRawText());
  return default(T);
}

you can use it like this code :

var model = new PropoertyValue();
model.Value = 0;
var jsonString = JsonSerializer.Serialize(model);
var data = JsonSerializer.Deserialize<PropoertyValue>(jsonString);
var yourObject = ((JsonElement)data.Value).ToObject<int>();

Now yourObject variable type is Int32.

You have another approach; you can use the second model for deserializing.

public class DeserializeModel {
  string Id {get;set;}
  JsonElement Value {get;set;}
  string Type {get;set;}
}

subsequently :

var model = new PropoertyValue();
model.Value = 0;
var jsonString = JsonSerializer.Serialize(model);
var data = JsonSerializer.Deserialize<DeserializeModel>(jsonString);
var yourObject = data.Value.ToObject<int>();
Morteza Asadi
  • 414
  • 3
  • 13