using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
public static void Main()
AlternateName = "The First Thing",
Description = "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
Console.WriteLine("--- Normal serialization using JsonIgnore and JsonConverter to reduce size ---");
Console.WriteLine(Serialize(foo, false));
Console.WriteLine("--- Ignoring JsonIgnore and JsonConverter attributes to get full JSON ---");
Console.WriteLine(Serialize(foo, true));
static string Serialize(object obj, bool includeEverything)
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new IgnoreJsonAttributesResolver();
return JsonConvert.SerializeObject(obj, settings);
public int Id { get; set; }
public string Name { get; set; }
public string AlternateName { get; set; }
[JsonConverter(typeof(StringTruncatingConverter))]
public string Description { get; set; }
public string Color { get; set; }
class IgnoreJsonAttributesResolver : DefaultContractResolver
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (var prop in props)
prop.PropertyName = prop.UnderlyingName;
class StringTruncatingConverter : JsonConverter
const int MaxLength = 45;
public override bool CanConvert(Type objectType)
return (objectType == typeof(string));
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
string s = (string)value;
if (s.Length > MaxLength) s = s.Substring(0, MaxLength);
public override bool CanRead
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
throw new NotImplementedException();