1

In Json.NET, how do I specify metadata, eg what properties to serialize, on classes not under my control, such as entity framework classes?

I could swear I've already read about a way, but I can't find it any more in the documentation.

Sorry in advance if I'm just being blind.

John
  • 6,693
  • 3
  • 51
  • 90

1 Answers1

2

Late reply, but better late than never.

You can map the classes not under your control to one you created/do control using AutoMapper, ValueInjector, etc. Then you are free to apply any attributes necessary.

Edit: Solution from JSON.NET Documentation using IContractResolver

public class DynamicContractResolver : DefaultContractResolver
{
  private readonly char _startingWithChar;
  public DynamicContractResolver(char startingWithChar)
  {
    _startingWithChar = startingWithChar;
  }

  protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
  {
    IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

    // only serializer properties that start with the specified character
    properties =
      properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();

    return properties;
  }
}

public class Book
{
  public string BookName { get; set; }
  public decimal BookPrice { get; set; }
  public string AuthorName { get; set; }
  public int AuthorAge { get; set; }
  public string AuthorCountry { get; set; }
}

IContractResolver Example

    Book book = new Book
{
  BookName = "The Gathering Storm",
  BookPrice = 16.19m,
  AuthorName = "Brandon Sanderson",
  AuthorAge = 34,
  AuthorCountry = "United States of America"
};

string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
  new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });

// {
//   "AuthorName": "Brandon Sanderson",
//   "AuthorAge": 34,
//   "AuthorCountry": "United States of America"
// }

string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
  new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });

// {
//   "BookName": "The Gathering Storm",
//   "BookPrice": 16.19
// }
DeveloperGuo
  • 636
  • 5
  • 15
  • Well ok, that's certainly a possibility in some scenarios. Especially in the case of entity classes, I really want them to remain the given ones. – John Oct 08 '13 at 15:37
  • Metadata can't be added at run-time - see [Can attributes be added dynamically in C#?](http://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c) Might be able to by extending existing JSON.net classes, but will have to take a look the library. – DeveloperGuo Oct 08 '13 at 16:46
  • They could have provided a different means to pass that kind of information to Json.NET. We don't have to use attributes for everything. – John Oct 12 '13 at 13:25
  • Nice choice of book ;) – Thomas Levesque Feb 03 '15 at 13:08