[Fork] https://stackoverflow.com/questions/46180408/configure-json-net-to-url-encode-certain-field

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
					
public class Program
{
	public static void Main()
	{
		var myObject = new MyModelClass("blablabla", "<>@%#^^@!%");
		
		string json = JsonConvert.SerializeObject(myObject, Formatting.Indented);
		
		Console.WriteLine(json);
	}
}


public class MyModelClass
{
    [JsonProperty("first_field")]
    public string FirstField { get; set; }

	[JsonIgnore]
	public string SecondField { get; set; }
	
	[JsonProperty("second_field")]
	private string UrlEncodedSecondField
	{
		get { return System.Web.HttpUtility.UrlEncode(SecondField); }
	}
	
    public MyModelClass(string first, string second)
    {
        FirstField = first;
        SecondField = second;
    }
}



// System.Web is not accessible in .Net Fiddle, so this is a shim to stand in for the HttpUtility class.
// This is for demonstration purposes only.  Do not use this in production code; use the real System.Web.HttpUtility class instead.
namespace System.Web
{
	public static class HttpUtility
	{
		public static string UrlEncode(string url)
		{
			StringBuilder sb = new StringBuilder();
			if (!string.IsNullOrEmpty(url))
			{
				foreach (char c in url)
				{
					if (IsUrlSafeChar(c))
						sb.Append(c);
					else
					{
						sb.Append('%');
						sb.Append(((int)c).ToString("X2"));
					}
				}
			}
			return sb.ToString();
		}
		
		private static bool IsUrlSafeChar(char c)
		{
			char[] safePunct = new char[] { '(', ')', '*', '-', '.', '!', '_' };
			return ((c >= 'a' && c <= 'z') ||
					(c >= 'A' && c <= 'Z') ||
					(c >= '0' && c <= '9') ||
					safePunct.Contains(c));
		}
	}
}
;