semver icon indicating copy to clipboard operation
semver copied to clipboard

docs/tip: Gist for JSON serializing with JSON.Net

Open madaz opened this issue 8 years ago • 4 comments

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.

madaz avatar Jul 27 '16 00:07 madaz

What version of JSON.NET are you using? Can you post a snippet of the raw json it creates?

niemyjski avatar Jul 27 '16 11:07 niemyjski

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"));

madaz avatar Jul 27 '16 22:07 madaz

Would be great to have this included in the semver library, enabled by default as when you serialize the classic old Version class

micdenny avatar Jun 10 '20 15:06 micdenny

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?

micdenny avatar Jun 10 '20 15:06 micdenny