Home > Mobile >  Map response string to an Object from POST request
Map response string to an Object from POST request

Time:05-11

I am trying to write a function that makes a Post requests and it returns as body data a person object. Normally would be used GET operation for this, but I am constrained to use POST because some technicalities.

   // HttpClient client = new HttpClient();
    public async Task<Person> PersonService()
    {
      var bodyObj = new Dictionary<string, string>();
      bodyObj ["user_id"] = "ac345adf3gj6";
      var serializedData = JsonSerializer.Serialize(bodyObj);
      var stringContet = new StringContent(serializedData, Encoding.UTF8, "application/json");
      var response = await client.PostAsync(url, data);
      var contents = await response.Content.ReadAsStringAsync();
      // map content to person object
      return person; // object mapped from content string
    }

Is there any way to wait for the data, map the string to a Person object and then return it as a Person object and not as a Task?

Something along these lines

 public Person PersonService() { ... return person; }

CodePudding user response:

In order to deserialize the content from JSON, you can use the ReadFromJsonAsync-method:

public async Task<Person> PersonService()
{
  var bodyObj = new Dictionary<string, string>();
  bodyObj ["user_id"] = "ac345adf3gj6";
  var serializedData = JsonSerializer.Serialize(bodyObj);
  var stringContet = new StringContent(serializedData, Encoding.UTF8, "application/json");
  var response = await client.PostAsync(url, data);
  // Change the following line: 
  var person = await response.Content.ReadFromJsonAsync<Person>();
  return person; // object mapped from content string
}
  • Related