简体   繁体   中英

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.

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.

            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

{
    "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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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