using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
public static void Main()
var myObject = new MyModelClass("blablabla", "<>@%#^^@!%");
var settings = new JsonSerializerSettings
ContractResolver = new CustomResolver(),
Formatting = Formatting.Indented
string json = JsonConvert.SerializeObject(myObject, settings);
public class MyModelClass
[JsonProperty("first_field")]
public string FirstField { get; set; }
[JsonProperty("second_field")]
public string SecondField { get; set; }
public MyModelClass(string first, string second)
public class UrlEncodeAttribute : Attribute { }
public class CustomResolver : DefaultContractResolver
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in props.Where(p => p.PropertyType == typeof(string)))
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null && pi.GetCustomAttribute(typeof(UrlEncodeAttribute), true) != null)
prop.ValueProvider = new UrlEncodingValueProvider(pi);
protected class UrlEncodingValueProvider : IValueProvider
PropertyInfo targetProperty;
public UrlEncodingValueProvider(PropertyInfo targetProperty)
this.targetProperty = targetProperty;
public void SetValue(object target, object value)
targetProperty.SetValue(target, (string)value);
public object GetValue(object target)
string value = (string)targetProperty.GetValue(target);
return System.Web.HttpUtility.UrlEncode(value);
public static class HttpUtility
public static string UrlEncode(string url)
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(url))
sb.Append(((int)c).ToString("X2"));
private static bool IsUrlSafeChar(char c)
char[] safePunct = new char[] { '(', ')', '*', '-', '.', '!', '_' };
return ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||