I need to serialize and deserialize an object that contains an System.Uri property using the latest (4.0.3) Json.NET library.
The following code demonstrates the problem:
string input = "http://test.com/%22foo+bar%22";
Uri uri = new Uri(input);
string json = JsonConvert.SerializeObject(uri);
Uri output = JsonConvert.DeserializeObject<Uri>(json);
The DeserializeObject method throws an JsonReaderException. This works fine with 4.0.2.
I’ve submitted an issue on codeplex with tests and patch to fix the issue, but it seems it takes a bit for the author to release a fixed version.
Meanwhile is there anything i can do ( using JsonSettings or anything else ) to make the latest version work as expected?
A few options i have so far:
- stick to 4.0.2 – new nuget packages depend on 4.0.3
- change uri to string – i rather go with option 1 and manually managed pkg dependencies
- use custom build with patch applied – this is what i’m doing now but i hate the idea of overriding the nuget package’s assemblies.
You can write a helper class that circumvents the usual handling of
System.Uriand treats it purely as a string, using theUri.OriginalStringproperty.Here’s a code sample that does exactly that with a converter class derived from Json.Net’s
JsonConverter.OriginalString Property (System.Uri) @ MSDN
One caveat is that you must update all places where you use JsonConvert to include the helper class as one of the extra
JsonConverterparameters.I’ve also added an example using Uri as a member variable in a class, to demonstrate that one wouldn’t necessarily have to override the attributes on a class, though it might be more convenient for you. If so, you could use
[JsonConverter(UriConverter)]as an attribute on members that need it.