我有一个名为CatalogSourceCodeItemsResponse的类。这是如何定义的:
public partial class CatalogSourceCodeItemsResponse
{
[System.Runtime.Serialization.OptionalFieldAttribute()]
private MMS.LoyaltyNext.API.SpendCard.MARSCatalog.CatalogFeed[] catalogFeedField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string endDateField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string sourceCodeField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string startDateField;
}
注意我无法修改/更新类,因为它来自服务。
我创建了一个web api,它向服务发出请求并返回此类作为响应。我的要求是,我不需要返回所有属性,而只需要第一个属性。
这是返回响应的代码:
[HttpGet]
public HttpResponseMessage GetCatalogItems()
{
CatalogSourceCodeItemsResponse response = new CatalogSourceCodeItemsResponse();
response = //logic to return the response from the service
return Request.CreateResponse<CatalogSourceCodeItemsResponse>(HttpStatusCode.OK, response);
}
当前输出
{
"catalogFeed" : null,
"endDate" : null,
"sourceCode" : null,
"startDate" : null
}
必需的输出是
{
"catalogFeed" : null
}
我怎样才能做到这一点?
答案 0 :(得分:2)
您可以使用ViewModel。
视图模型仅表示要在视图/页面上显示的数据,无论是用于静态文本还是用于输入值(如文本框和下拉列表)。
public partial class CatalogSourceCodeItemsResponse
{
[System.Runtime.Serialization.OptionalFieldAttribute()]
private MMS.LoyaltyNext.API.SpendCard.MARSCatalog.CatalogFeed[] catalogFeedField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string endDateField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string sourceCodeField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string startDateField;
}
视图模型与域模型的不同之处在于,视图模型仅包含要在视图上使用的数据(由属性表示)。例如,假设您只想在CatalogSourceCodeItemsResponse记录中显示一个项目,您的视图模型可能如下所示:
public class CatalogSourceCodeItemsResponseViewModel
{
private MMS.LoyaltyNext.API.SpendCard.MARSCatalog.CatalogFeed[] catalogFeedField; { get; set; }
}
然后您的控制器操作将变为
[HttpGet]
public HttpResponseMessage GetCatalogItems()
{
CatalogSourceCodeItemsResponse response = new CatalogSourceCodeItemsResponse();
response = //logic to return the response from the service
CatalogSourceCodeItemsResponseViewModel responseViewModel=new CatalogSourceCodeItemsResponseViewModel();
responseViewModel.catalogFeedField=response.catalogFeedField;
return Request.CreateResponse<CatalogSourceCodeItemsResponseViewModel>(HttpStatusCode.OK, responseViewModel);
}