从ToString方法序列化类

时间:2015-03-31 22:34:07

标签: c#

我使用JSon.Net来序列化ViewModel:

public class ViewModel {
   public Int32 Id { get; set; }
   // other properties
}

public static class ViewModelExtensions {

  public static IHtmlString ToJson(this ViewModel model) {

    JsonSerializerSettings settings = new JsonSerializerSettings {
      ContractResolver = new CamelCasePropertyNamesContractResolver()
    };

    return MvcHtmlString.Create(JsonConvert.SerializeObject(model, settings));

  } // ToJson

} // ViewModelExtensions

我可以使用在ViewModel类中添加方法ToString来序列化类本身,而不是使用扩展模型吗?

我该怎么做?什么是最好的选择?

2 个答案:

答案 0 :(得分:1)

默认的ToString是一个虚函数,所以你应该能够通过这样做来覆盖它:

override public string ToString() {
    return [Your format logic here];
}

我认为这就是你想要的。

答案 1 :(得分:0)

根据我收到的评论,我刚刚结束了以下内容:

public class ViewModel {

  public IHtmlString ToJson() {
    return ToJson(new CamelCasePropertyNamesContractResolver());
  } // ToJson

  public IHtmlString ToJson(IContractResolver resolver) {
    JsonSerializerSettings settings = new JsonSerializerSettings {
      ContractResolver = resolver 
    };
    return MvcHtmlString.Create(JsonConvert.SerializeObject(this, settings));

  } // ToJson

} // ViewModel