semver
semver copied to clipboard
docs/tip: Gist for JSON serializing with JSON.Net
Custom converter for serializing to Json using http://www.newtonsoft.com/json.
This is an enhancement of the Newton.Json.Converters.VersionConverter
.
https://gist.github.com/madaz/efab4a5554b88dc2862d58046ddba00f
Reason Without the custom serializer, the default would create a nested "SemVersion" property inside the original property when serializing.
The default deserialzing worked fine.
What version of JSON.NET are you using? Can you post a snippet of the raw json it creates?
Environment
.Net 4.6
semver 1.1.2
Newtonsoft.Json 9.0.1
also tried Newtonsoft.Json 7.0.1
Scenario
public class Manifest
{
public string Name { get; set; }
public SemVersion Version { get; set; }
}
var manifest = new Manifest
{
Name = "foo-bar",
Version = SemVersion.Parse("1.0.0")
};
var json = JsonConvert.SerializeObject(manifest, Formatting.Indented);
output Creates an extra SemVersion nested property under Version
{
"Name": "foo-bar",
"Version": {
"SemVersion": "1.0.0"
}
}
Expected output
{
"Name": "foo-bar",
"Version": "1.0.0"
}
Workaround
var manifest = new Manifest
{
Name = "foo-bar",
Version = SemVersion.Parse("1.0.0")
};
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new SemVersionConverter()); // SemVesrionConverter https://gist.github.com/madaz/efab4a5554b88dc2862d58046ddba00f
var json = JsonConvert.SerializeObject(manifest, Formatting.Indented, settings);
Note: Deserialize works as expected using JSON.Net with out any workarounds
string raw = @"{
""Name"": ""foo-bar"",
""Version"": ""1.0.0""
}";
var manifest = JsonConvert.DeserializeObject<Manifest>(raw);
Trace.WriteLine(manifest.Version == SemVersion.Parse("1.0.0"));
Would be great to have this included in the semver library, enabled by default as when you serialize the classic old Version
class
Why the Version
class is serialized as excepted? Probably is a known type of Newtonsoft Json library and there is a default converter for it?