具有null属性的Base类中的类

时间:2016-03-04 17:06:38

标签: c#

我有以下界面:

public interface IResponse<T> {
  IList<Error> Errors { get; }
  IPaging Paging { get; }
  IList<T> Result { get; }    
}

及其实施:

public class Response<T> : IResponse<T> {

  IList<Error> Errors { get; private set; }
  public IPaging Paging { get; private set; }
  public IList<T> Result { get; private set; }

  public Response(IList<T> result, IPaging paging, IList<Error> errors) {
    Errors = errors;
    Paging = paging;
    Result = result;
  }

}

所以我按如下方式使用它:

Response<MyModel> response = new Response<MyModel>();

在某些情况下,我需要创建一个响应,其中我没有T和Paging,Result为null ...它们为null但仍存在于对象中。

Response response = new Response();

我所拥有的不会工作(我认为。在这种情况下,没有模型):

Response<?> response = new Response<?>();

原因是我会将响应转换为JSON,我仍然希望显示Paging和Result。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

如果您使用Newtonsoft进行序列化,则不需要对模型进行任何代码更改,您可以执行以下操作:

void Main() {
    Response<MyResponse> myResponse = new Response<MyResponse>(new List<MyResponse>(), null, null);
    var serializer = new JsonSerializer();
    StringBuilder sb = new StringBuilder();

    using(var writer = new StringWriter(sb)) {
        using (var jWriter = new JsonTextWriter(writer)) {
            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.Serialize(jWriter, myResponse);
        }
    }

    Console.WriteLine(sb.ToString());
}

public interface IResponse<T> {
  IList<Error> Errors { get; }
  IPaging Paging { get; }
  IList<T> Result { get; }    
}

public class Response<T> : IResponse<T> {

  public IList<Error> Errors { get; private set; }
  public IPaging Paging { get; private set; }
  public IList<T> Result { get; private set; }

  public Response(IList<T> result, IPaging paging, IList<Error> errors) {
    Errors = errors;
    Paging = paging;
    Result = result;
  }

}

public class Error {


}

public interface IPaging {

}

public class MyResponse {
    public string Name {get; set;}
}

运行上面的代码会产生以下输出:

{"Result":[]}

通过更改此行上的序列化设置:

serializer.NullValueHandling = NullValueHandling.Ignore;

serializer.NullValueHandling = NullValueHandling.Include;

结果变为:

{"Errors":null,"Paging":null,"Result":[]}