Matteo Fioroni
Matteo Fioroni

Reputation: 103

System.Text.Json Custom Seriallization / Deserialization

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?

Upvotes: 0

Views: 289

Answers (1)

Morteza Asadi
Morteza Asadi

Reputation: 433

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>();

Upvotes: 2

Related Questions