如何解决如何将WebAPI结果反序列化或格式化为特定的json结构 DTO ViewModel 反序列化对DTO的响应将DTO映射到ViewModel
我正在使用.net核心3.1 Web API。这是从外部API获取数据。以下是我的代码控制器部分
[HttpGet("transinfo/{id}")]
public Object GettransactionData(int id)
{
var result=_transaction.GettransactionDetails(id).Result;
List<PipeLineResponse> P = JsonConvert.DeserializeObject<List<PipeLineResponse>>(result.ToString());
PipeLineResponseObject P1 = new PipeLineResponseObject();
P1.data = P;
return P1;
}
我的服务代码如下
public async Task<Object> GettransactionDetails(int id)
{
string request=//fetched from db
var stringContent = new StringContent(request);
Client = utilities.GetHttpClient();
string apiEndpoint=//External API URL
HttpResponseMessage httpResponseMessage = await Client.PostAsync(apiEndpoint,stringContent);
if (httpResponseMessage.IsSuccessStatusCode)
{
return await httpResponseMessage.Content.ReadAsAsync<Object>();
}
}
但是我得到以下格式的结果(邮递员的回复)
{
"data": [
{
"Tranid": "34540d40-7db8-44c1-9a2a-5072c2d01756","fields": {
"Fields.10": "1001","Fields.11": "Test1","Fields.12": "Fixed1"
}
},{
"Tranid": "145800f9-c4a5-4625-84d7-29af5e674a14","fields": {
"Fields.10": "1002","Fields.11": "Test2","Fields.12": "Fixed2"
}
}
]
}
但是我需要以下格式的数据
{
"data": [
{
"TransactionID": "34540d40-7db8-44c1-9a2a-5072c2d01756","fieldsList": [
{
"fieldId": "10","fieldValue": "1001"
},{
"fieldId": "11","fieldValue": "Test1"
},{
"fieldId": "12","fieldValue": "Fixed1"
}
]
},{
"TransactionID": "145800f9-c4a5-4625-84d7-29af5e674a14","fieldValue": "1002"
},"fieldValue": "Test2"
},"fieldValue": "Fixed2"
}
]
}
]
}
我该如何实现?可以使用JObject或JArray反序列化吗?请帮忙。 我试图创建以下模型类,并尝试反序列化,但未获得预期的结果。
public class PipeLineResponse
{
public string TransactionID { get; set; }
public List<Dictionary<string,string>> fields { get; set; }
}
public class PipeLineResponseObject
{
public List<PipeLineResponse> data { get; set; }
}
如何以任何DTO或Automapper的格式创建该json?请帮我提供样品。
解决方法
我在这里提出的解决方案采用DTO
方法。服务的响应正在反序列化到DTO,DTO进一步被手动映射到我们发送给客户端的最终ViewModel
。 绝不意味着此实现已可以投入生产,并且还有改进的余地,对此我要添加一些评论。但是,这使我们对如何处理这种情况有了详细的了解。我们正在使用Newtonsoft.Json
,可以通过NuGet
程序包管理器将其导入您的项目。 >
DTO
的结构
// RootDTO.cs
// This structure is directly based on the response obtained from remote service.
public class Fields
{
[JsonProperty(PropertyName ="Fields.10")]
public string Fields10 { get; set; }
[JsonProperty(PropertyName = "Fields.11")]
public string Fields11 { get; set; }
[JsonProperty(PropertyName = "Fields.12")]
public string Fields12 { get; set; }
}
public class Datum
{
public string Tranid { get; set; }
public Fields fields { get; set; }
}
public class RootDTO
{
[JsonProperty(PropertyName ="data")]
public List<Datum> data { get; set; }
}
ViewModel
的结构
// PipelineResponse.cs
public class FieldsList
{
public string fieldId { get; set; }
public string fieldValue { get; set; }
}
public class ResponseDatum
{
[JsonProperty(PropertyName = "TransactionID")]
public string TransactionID { get; set; }
public List<FieldsList> fieldsList { get; set; }
}
public class PipelineResponse
{
public List<ResponseDatum> data { get; set; }
}
反序列化对DTO
的响应
// ...other code
var responseString = await httpResponseMessage.Content.ReadAsAsync<Object>();
// This is where the DTO object is created. This should be mapped to view model type.
var responseDTO = JsonConvert.DeserializeObject<RootDTO>(responseString);
将DTO
映射到ViewModel
在将响应发送到客户端之前,需要完成从DTO类型到ViewModel类型的映射。它是发送给客户端的视图模型类型。可以将这种逻辑放置在单独的帮助器中(理想情况下,可以将关注点分开),也可以根据您的实践放置在任何其他位置。
public PipelineResponse ConvertResponseDTOToResponse(RootDTO responseDTO)
{
// FieldId is being hardcoded here. Instead,you can use Reflection to
// fetch the property name,split on '.' and take the item at index 1.
// Notice that DTO properties have "JsonProperty" attributes for this.
try
{
List<ResponseDatum> responseList = new List<ResponseDatum>();
if (responseDTO != null)
{
// Reflection can be used to avoid hardcoding on 'fieldId'
foreach (var item in responseDTO.data)
{
var responseDataObj = new ResponseDatum
{
TransactionID = item.Tranid,fieldsList = new List<FieldsList>
{
new FieldsList
{
fieldValue = item.fields.Fields10,fieldId = "10"
},new FieldsList
{
fieldValue = item.fields.Fields11,fieldId = "11"
},new FieldsList
{
fieldValue = item.fields.Fields12,fieldId = "12"
}
}
};
responseList.Add(responseDataObj);
}
}
// This object is what you return from your controller endpoint finally.
// The serialized response of this object is of the json structure you need
return new PipelineResponse { data = responseList };
}
catch (Exception ex)
{
throw ex;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。