Skip to content

Instantly share code, notes, and snippets.

@westonal
Created July 6, 2015 10:59
Show Gist options
  • Save westonal/2f22d5b455b72c54cf0b to your computer and use it in GitHub Desktop.
Save westonal/2f22d5b455b72c54cf0b to your computer and use it in GitHub Desktop.
Add a property to Json on serialize
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NUnit.Framework;
namespace AddToJsonPoco
{
[TestFixture]
public class AddPropertyToJsonOnSerialize
{
[Test]
public void Without()
{
var model = new Model {id = 123};
var json = JsonConvert.SerializeObject(model);
Assert.AreEqual("{\"id\":123}", json);
}
private readonly JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new AppendProperties(
new JsonProperty
{
PropertyName = "I do not exist",
Readable = true,
Writable = false,
PropertyType = typeof (string),
ValueProvider = new FixedValueProvider("hello!")
})
};
[Test]
public void With()
{
var model = new Model {id = 123};
var json = JsonConvert.SerializeObject(model, _jsonSerializerSettings);
Assert.AreEqual("{\"id\":123,\"I do not exist\":\"hello!\"}", json);
}
}
public class Model
{
public int id;
}
public sealed class AppendProperties : DefaultContractResolver
{
private readonly JsonProperty[] _jsonProperties;
public AppendProperties(params JsonProperty[] jsonProperties)
{
_jsonProperties = jsonProperties;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var res = base.CreateProperties(type, memberSerialization);
foreach (var jsonProperty in _jsonProperties)
res.Add(jsonProperty);
return res;
}
}
public sealed class FixedValueProvider : IValueProvider
{
private readonly object _value;
public FixedValueProvider(object value)
{
_value = value;
}
public void SetValue(object target, object value)
{
throw new NotImplementedException();
}
public object GetValue(object target)
{
return _value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment