none
convert object to model RRS feed

  • Question

  • Hi

    I have function returning an Object . I need to map it to the model MyModel. like: 

    public static async Task<Object> SendPost(Object request, string requestUri)
            {
                try
                {
                   //... 
                    HttpResponseMessage response = await client.PostAsJsonAsync(requestUri, request);
                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        var datastring = (response.Content.ReadAsStringAsync().Result);
                        return  JsonConvert.DeserializeObject<Object>(datastring);
                    }
    
                    return response;
                }
                catch(Exception exc)
                {
                    return exc;
                }
            }

    Then I need to get the data

     var response1=HttpContext.SendPost(myRequest, "myUrl").Result;
    then I need to load this result to MyModel:

    class MyModel    {
            public int id { get; set; }
            public string title { get; set; }
            public string description { get; set; }
            public List<string> images { get; set; }
               }
    Please advice how do I transfer object in myModel?


    • Edited by Barbi Rio Monday, December 24, 2018 7:43 AM
    Monday, December 24, 2018 7:42 AM

Answers

  • How your json looks like ? If it comes with the names as in your model you can directly deserialize json in your  model.

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by Barbi Rio Wednesday, December 26, 2018 5:42 AM
    Monday, December 24, 2018 8:27 AM

All replies

  • How your json looks like ? If it comes with the names as in your model you can directly deserialize json in your  model.

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by Barbi Rio Wednesday, December 26, 2018 5:42 AM
    Monday, December 24, 2018 8:27 AM
  • public DtoProject GetProjByIdApi(int id)
            {
                DtoProject dto;
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://progmgmntcore2api.com/api/project/GetProjById?id=" + id);
                    HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
    
                    if (!getResponseMessage.IsSuccessStatusCode)
                        throw new Exception(getResponseMessage.ToString());
    
                    var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
    
                    dynamic project = JsonConvert.DeserializeObject(responsemessage);
    
                    dto = project.ToObject<DtoProject>();
                }
    
                return dto;
            }
    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }
    


    Monday, December 24, 2018 12:09 PM
  • That is a bad way of doing things. You shouldn't be returning raw Object types and then expect the calling code to handle the conversion. This is not type safe, leads to more code overall, is harder to use in clients and is not flexible to changes later on. Use a generic method at a minimum although there are already implementations for this. Here's a link to the version(s) that I use. How I use them.

    //Calling code should be using a client so they don't worry about HTTP
    public class MyClient
    {
       public MyClient ( HttpClient client )
       {
          _client = client;
       }
    
       public async Task<MyModel> Update ( MyData data, CancellationToken cancellationToken )
       {
          var request = new { Id = data.Id, Name = data.Name };
          var response = await _client.PostJsonAsync("resource", request, cancellationToken).ConfigureAwait(false);
    
          //Validate response
          await response.ThrowIfErrorAsync().ConfigureAwait(false);
          return await response.HandleJsonAsync<MyModel>(cancellationToken).ConfigureAwait(false);
       }
    
       private readonly HttpClient _client;
    }



    Michael Taylor http://www.michaeltaylorp3.net

    Monday, December 24, 2018 5:37 PM
    Moderator
  • public DtoProject GetProjByIdApi(int id)
            {
                DtoProject dto;
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://progmgmntcore2api.com/api/project/GetProjById?id=" + id);
                    HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
    
                    if (!getResponseMessage.IsSuccessStatusCode)
                        throw new Exception(getResponseMessage.ToString());
    
                    var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
    
                    dynamic project = JsonConvert.DeserializeObject(responsemessage);
    
                    dto = project.ToObject<DtoProject>();
                }
    
                return dto;
            }
    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }


    No this is not my point. I want send request to be able to send different classes, to be able to send user login, post products,  post invoices...

    • Edited by Barbi Rio Wednesday, December 26, 2018 5:06 AM
    Wednesday, December 26, 2018 5:05 AM
  • No this is not my point. I want send request to be able to send different classes, to be able to send user login, post products,  post invoices...

    Your approach is unorthodox and not optimal IMO. So you're going to have some kind of a generic solution? How do you know which object is coming across? How are you going to know what you were doing if it blows up and throws an exception?  

    You don't return an exception, you throw an exception at that point.

    Wednesday, December 26, 2018 6:52 AM
  • Instead returning Task<Object> I'm returning Task<string> and I'm deserializing Json after SendPost
    Wednesday, December 26, 2018 7:35 AM
  • Instead returning Task<Object> I'm returning Task<string> and I'm deserializing Json after SendPost

    What difference does that make? You still have to know what object you are going to construct as you deserialize the Json into an object with unnecessary and complicated code for something that you are trying to do generically. 

    You wouldn't make it out of a code review IMO.

    Wednesday, December 26, 2018 8:02 AM