Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
madaz opened this issue Jul 27, 2016 · 4 comments
Open

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

madaz opened this issue Jul 27, 2016 · 4 comments

Comments

@madaz
Copy link

madaz commented Jul 27, 2016

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.

@niemyjski
Copy link
Collaborator

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

@madaz
Copy link
Author

madaz commented Jul 27, 2016

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

@micdenny
Copy link

micdenny commented Jun 10, 2020

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

@micdenny
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants