using System.Collections.Generic;
public class StringsWithoutNonprintablesConverter : JsonConverter<string>
public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
if (reader.TokenType != JsonToken.String)
throw new System.IO.InvalidDataException("Json data is not a string value");
var s = (string) reader.Value;
return (s.Any(char.IsControl)) ? new string(s.Where(c => !char.IsControl(c)).ToArray()) : s;
public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
writer.WriteValue(value);
public static void Main()
""1"": ""\t\tSay \""Hello\""\n\u0010\n"",
""2"": ""Something with non-printable\ncontrol\tchar sequences"",
""3"": ""Something with printable control ch\u0061r sequences"",
""4"": ""Something with both non-printable and printable\u0009control ch\u0061r sequences""
Console.WriteLine("The source json:");
Console.WriteLine("---------------------------------------------");
Console.WriteLine("The deserialization result without filtering:");
var dict = JsonConvert.DeserializeObject <Dictionary<string, string>>(json);
foreach (var kvp in dict)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
Console.WriteLine("---------------------------------------------");
Console.WriteLine("The deserialization result with filtering:");
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
Converters = new[] { new StringsWithoutNonprintablesConverter() }
dict = JsonConvert.DeserializeObject <Dictionary<string, string>>(json);
foreach (var kvp in dict)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");