I think that you must find a way to not include “Algo”=”” when there is an “Instance”=”someInstanceValue” in JSON, because in will overwrite the value of Instance on deserialization. One of approaches is using a Contract Resolver:
public class MyContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties( Type type, MemberSerialization memberSerialization )
{
var list = base.CreateProperties( type, memberSerialization );
foreach( var p in list.Where( p => p.PropertyName == "Algo" || p.PropertyName == "Instance" ) )
{
p.DefaultValue = "";
p.DefaultValueHandling = DefaultValueHandling.Ignore;
p.NullValueHandling = NullValueHandling.Ignore;
}
return list;
}
}
Usage:
JsonSerializerSettings opt = new JsonSerializerSettings
{
ContractResolver = new MyContractResolver( ),
};
string jsonConvertStr = JsonConvert.SerializeObject( request, opt );
Request requestJsonConvert = JsonConvert.DeserializeObject<Request>( jsonConvertStr, opt );
Perhaps it can be improved, or there are more appropriate ways. (Maybe there is a forum, which is dedicated to these aspects).