John Gietzen
John Gietzen

Reputation: 49544

Can I override the Json.Net member-name mapping, within the context of a single serializer?

I'm trying to write documents into CouchDB in .NET, but my I don't want to mark all of my Id properties with [JsonProperty(MemberName = "_id")], since I need to serialize them normally (with the member name being Id) to send them out via my own HTTP API.

Basically, I want this:

var serializer = new JsonSerializer();
/* some magic happens */
serializer.Serialize(textWriter, new Thing { Id = "foo", Value = "bar" });

To result in this:

{_id:"Foo",Value:"Bar"}

But without the magic joojoo, it should still be this:

{Id:"Foo",Value:"Bar"}

I'm assuming that this shouldn't be too hard, but I don't know my way around the internals of Json.Net well enough to Just Do It™.

Upvotes: 3

Views: 637

Answers (1)

Marc
Marc

Reputation: 6771

First create a ContractResolver:

public class IdContractResolver : DefaultContractResolver
{
    protected override string ResolvePropertyName(string propertyName)
    {
        if (propertyName == "Id") return "_id";
        return base.ResolvePropertyName(propertyName);
    }
}

Then add the magic by attaching it:

var serializer = new JsonSerializer();
serializer.ContractResolver = new IdContractResolver();
serializer.Serialize(textWriter, new Thing { Id = "foo", Value = "bar" });

And you get:

{_id:"Foo",Value:"Bar"}

Upvotes: 3

Related Questions