I've a class, that tries to serialize and deserialize objects, given to it, using Json.net
public class JsonSerializer
{
public string Serialize(object toSerialaze)
{
return JsonConvert.SerializeObject(toSerialaze);
}
public T Deserialize<T>(string toDeserialaze)
{
return JsonConvert.DeserializeObject<T>(toDeserialaze);
}
}
And giving to it anobject of such a class
public class Isbn
{
private readonly int _groupCode;
private readonly int _publisherCode;
private readonly int _titleCode;
private readonly int _checkCode;
private static readonly Regex Regex = new Regex(@"^\s*\d*\s*-\s*\d*\s*-\s*\d*\s*-\s*\d*\s*$");
public Isbn(int groupCode, int publisherCode, int titleCode, int checkCode)
{
_groupCode = groupCode;
_publisherCode = publisherCode;
_titleCode = titleCode;
_checkCode = checkCode;
}
public Isbn(string isbn)
{
if (isbn == null)
throw new ArgumentNullException("isbn");
if (isbn == "") return;
if (!IsValid(isbn)) return;
var isbnStrings = isbn.Split(new[] {'-', ' '}, StringSplitOptions.RemoveEmptyEntries);
_groupCode = Convert.ToInt32(isbnStrings[0]);
_publisherCode = Convert.ToInt32(isbnStrings[1]);
_titleCode = Convert.ToInt32(isbnStrings[2]);
_checkCode = Convert.ToInt32(isbnStrings[3]);
}
}
I get the following exception:
Additional information: Unable to find a constructor to use for type Library.Isbn. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.
I know, I may put [JsonConstructor]
before the constructor I need to use while deserialization, but I don't want class Isbn
to know about Json.
How may I achieve the same behavior in another way? How may I let JsonConverter know, which of 2 constructors to use?