在没有注释的情况下指定Json.net元数据的替代方法?

时间:2012-12-12 15:45:20

标签: json.net

在Json.NET中,如何在不受我控制的类上指定元数据,例如要序列化的属性,例如实体框架类?

我可以发誓我已经读过一些方法,但我在文档中找不到它。

如果我只是失明,请提前抱歉。

1 个答案:

答案 0 :(得分:2)

迟到的回复,但迟到总比没有好。

您可以使用AutoMapper,ValueInjector等将不受您控制的类映射到您创建/控制的类。然后您可以自由应用任何必要的属性。

编辑: 使用IContractResolver

从JSON.NET文档中获得解决方案
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示例

    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
// }