Serialize null reference object
I am trying to "serialize" a specific type by iterating over its properties and writing each value type into a dictionary.
Pseudo
serialize(object)
foreach(prop in object.GetType().GetProperties()
value = prop.GetValue(object);
if (prop.PropertyType.isValueType)
writeToDict(prop.Name, value)
else
serialize(value)
specified type
public class ComplexType {
public string Prop1 { get; set; }
public int Prop2 { get; set; }
public OtherType Prop3 { get; set; }
}
public class OtherType {
public string Prop4 { get; set; }
}
Now when I instantiate ComplexType
and try to "serialize" it, it works fine until it repeats through Prop3
( OtherType
). When I try to call value.GetType()
on it, I am in NullReferenceException
, because of course there has never been a set of references to Prop3
.
Is there a way to get around this? How do other serialization frameworks do it? (I mean, I can't even create a default instance of this type because I don't know the type at runtime!)
Oh, and yes, I cannot skip the property because I am interested in the structure (even if it has no value).
Ok I figured it out. NullReferenceException
happened because I was stupid.
For those trying to get the type of an uninitialized reference type in the future:
If you call .GetType()
on an object, the .NET frameworks look at the reference to that object in memory. Since the object has not been initialized, there is nothing to look for, so it gets called NullReferenceException
. If you want to iterate over the instance properties, you need at least the type of the top majority of the parent, then you can get the types of the additional properties of the reference type through PropertyInfo.PropertyType
(and not directly from the object you pulled from the parent property).
Well I came across this issue when it was already resolved by the starter. Just wondering if the standard approach using the json serializer is fine. Smth very simple like
var newObjectOfComplexType = new ComplexType()
{
Prop1 = "Prop1Value",
Prop2 = 3,
Prop3 = new OtherType() {Prop4 = "Prop4Value"}
};
var serializedResult = JsonConvert.SerializeObject(newObjectOfComplexType);
will give a result very similar to what you were looking for:
{"Prop1":"Prop1Value","Prop2":3,"Prop3":{"Prop4":"Prop4Value"}}
source to share