Reputation: 1399
I am coding a bunch of the following type of classes and it just seems a bit smelly to me. Basically I want to deserialze based on some json configuration of properties as well as serialize it for storage. I thought the following method would work well since I don't want to stipulate that the serialization/deserialization has to be json etc.
The code looks like this for a simple object:
public class IntegerDatasourceInstanceOptions
{
public int Start { get; set; }
public int Count { get; set; }
public IntegerDatasourceInstanceOptions()
{
}
public IntegerDatasourceInstanceOptions(string config)
{
var options = JsonConvert.DeserializeObject<IntegerDatasourceInstanceOptions>(config);
if (options != null)
{
Start = options.Start;
Count = options.Count;
}
}
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
I guess I'm just looking for some feedback as to whether this is the best way to go or not.
Upvotes: 0
Views: 60
Reputation: 29668
I tend to use a static method in instances like this, for example:
public class IntegerDatasourceInstanceOptions
{
public int Start { get; set; }
public int Count { get; set; }
public IntegerDatasourceInstanceOptions()
{
}
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
public static IntegerDatasourceInstanceOptions Create(string config)
{
return JsonConvert.DeserializeObject<IntegerDatasourceInstanceOptions>(config);
}
}
You can then just do:
var options = IntegerDatasourceInstanceOptions.Create("{...}");
Upvotes: 2