0

I hope you can help me. I'm trying to deserialize a response object into a dynamic object in C#. The code goes as follow:

var result = await message.Content.ReadAsStringAsync();
dynamic response = JsonConvert.DeserializeObject<dynamic>(result);

foreach (dynamic backgroundTaskURL in response)
{
    filaUPloads.Add(backgroundTaskURL.href);
}

The response dynamic object above has the following value:

{{
    "href": "/me/background-tasks/77fa9922-5a1b-4fce-ada4-7c5c5d093270"
}}

At the first foreach interaction, the backgroundTaskURL dynamic object reads:

{
    "href": "/me/background-tasks/77fa9922-5a1b-4fce-ada4-7c5c5d093270"
}

For some reason I'm not able to understand, the backgroundTaskURL dynamic object is not resolving the "href" property.

Please advise! Thanks!

maccettura
  • 10,514
  • 3
  • 28
  • 35
  • You've encountered one of the problems with `dynamic` -- you never know what you have. In your case the returned `response` is **not an array** it's a single object, so you need to do `filaUPloads.Add(response.href);` without the loop. – dbc Oct 23 '19 at 21:00

2 Answers2

0

If you're using Newtonsoft.Json, you could use a JObject instead, which I believe is just a JSON-map-like abstraction over a dynamic object.

var result = await message.Content.ReadAsStringAsync();
dynamic response = JsonConvert.DeserializeObject<JObject>(result);

foreach (var backgroundTaskURL in response)
{
    filaUPloads.Add(backgroundTaskURL["href"]);
}
gabriel.hayes
  • 2,267
  • 12
  • 15
0

Try the following

 public class ListRecev
    {
        public string href { get; set; }

    }
  var resultjson = JsonConvert.DeserializeObject<ListRecev>(result);
  foreach (var backgroundTaskURL in resultjson)
  {
   filaUPloads.Add(backgroundTaskURL.href);
  }
Manny
  • 143
  • 1
  • 7