我有一个返回HoursReport对象的Web服务:
public class HoursReport
{
public List<Client> MyClients { get; set; }
public String Start {get; set;}
public String End {get; set;}
public String Key {get; set;}
public String DontIncludeMe {get; set;}
}
这是我设置的界面:
[OperationContract]
[WebGet(UriTemplate = "Punches/{clientId}?start={start}&end={end}&raw={raw}")]
[Description("Retrieve hours information for each client.")]
HoursReport Punches(string start, string end, string clientId, string raw);
我的问题是:我可以只返回一小部分的HoursReport对象吗?我可以动态决定哪个部分吗?
答案 0 :(得分:0)
简短回答:
不,你不能
如果你覆盖API的返回功能
,你可以尽快回答如果你使用NewtoinJson:
var serializer = new JsonSerializer();
response.ClearContent();
response.ContentType = "application/json";
using (var sw = new StreamWriter(response.OutputStream))
{
using (var writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, new { Start = “lol”, Key=”myKey”, MyClients = myList });
}
}
编辑:我使用此函数来更改我的Json返回:
public static class ServicesHelper
{
public static void SendJson(HttpResponse response, object data)
{
var serializer = new JsonSerializer();
//serializer.Converters.Add(new JavaScriptDateTimeConverter());
response.ClearContent();
response.ContentType = "application/json";
using (var sw = new StreamWriter(response.OutputStream))
{
using (var writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, data);
}
}
}
public static string ToJson(object data)
{
return JsonConvert.SerializeObject(data);
}
}
答案 1 :(得分:0)
不直接。实现此目的的最佳方法是将所有第三方依赖项对象视为不应由API客户端直接使用的内容。当您创建一个表示要返回的JSON结构的新对象时,您可以将其装饰为仅序列化这些属性。
要在第三方依赖对象和API对象之间移动数据,请查看Mapper模式之类的内容。它接收第三方依赖对象并将其转换为新对象。
示例:
public class HoursReport
{
public List<Client> MyClients { get; set; }
public String Start {get; set;}
public String End {get; set;}
public String Key {get; set;}
public String DontIncludeMe {get; set;}
}
public class HoursReportResponse
{
[JsonProperty(PropertyName="start")]
public string Start {get; set;}
[JsonProperty(PropertyName="end")]
public string End {get; set;}
}
public class HoursReportMapper
{
public HoursReportResponse Map(HoursReport hoursReport)
{
return new HoursReportResponse
{
Start = hoursReport.Start,
End = hoursReport.End
};
}
}