如何将json响应传递给ASP.Net MVC中的模型?

时间:2019-05-07 03:32:56

标签: asp.net json asp.net-mvc httpresponse

我很难将JSON值传递给模型。

我已经尝试解析JSON响应并将值传输到变量,并且效果很好,但是我要做的就是将值传输到模型。

            var transno = "ST-100420190001";

            var client = new HttpClient();
            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri("https://myurl.com/" + transno),
                Headers = {
                { HttpRequestHeader.Accept.ToString(), "application/json" },
                { HttpRequestHeader.ContentType.ToString(), "application/json"},
                { "client-id", "client_id"},
                { "client-secret","client_secret"},
                { "partner-id","partner_id"},
                { "X-Version", "1" }
            }
            };

            var response = client.SendAsync(httpRequestMessage).Result;
            var payload = JObject.Parse(await response.Content.ReadAsStringAsync());  

Postman上的JSON响应

{
    "records": [
        {
            "transferId": "YU6411649475339",
            "type": "Payment",
            "createdAt": "2018-08-10T08:40:46.000Z",
            "dateUpdated": "",
            "state": "Sent for Processing",
            "senderTransferId": "ST-100420190001"
        }
    ],
    "totalRecords": 1
}

2 个答案:

答案 0 :(得分:1)

首先,您需要创建模型以保存json响应。根据您的输出,您的模型应具有以下格式。

public class Record
{
    public string transferId { get; set; }
    public string type { get; set; }
    public DateTime createdAt { get; set; }
    public string dateUpdated { get; set; }
    public string state { get; set; }
    public string senderTransferId { get; set; }
}

public class RootObject
{
    public List<Record> records { get; set; }
    public int totalRecords { get; set; }
}

为您的有效负载对象分配模型:

RootObject obj= JsonConvert.DeserializeObject<RootObject>(response.Content);

答案 1 :(得分:0)

使用javascript序列化程序。

示例:

  var json = new JavaScriptSerializer().Serialize('values');

  var contents = new StringContent(json.ToString(), Encoding.UTF8, "application/json");

然后

var respo = await client.PostAsync("https://myurl.com/", contents);