简体   繁体   English

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

[英]How to pass json response to a model in ASP.Net MVC?

I'm having a hard time on passing the JSON values to a model. 我很难将JSON值传递给模型。

I've already tried to parse the JSON response and transfer the values to a variable and it works well but what I want to do is to transfer the values to a model. 我已经尝试解析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());  

The JSON Response on Postman looks like this Postman上的JSON响应如下所示

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

First you need to create model to hold you json response. 首先,您需要创建模型来保存json响应。 as per your output your model should have following format. 根据您的输出,您的模型应具有以下格式。

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; }
}

assign your payload object to model: 将您的有效负载对象分配给模型:

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

Use javascript serializer. 使用javascript序列化器。

Example: 例:

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

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

then 然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM