0

I read a lot of articles about JSON to C# conversion but I have one specific problem. I'm trying to convert JSON from Http response to C# object of NewsResult type with following line of code :

var newsResult = await response.Content.ReadAsAsync<NewsResult>();

This code works in most of cases and map automatically JSON data to hierarchy of C# objects, but in one case REST returns following JSON:

{
"result": {
    "1": {
        "id": 1,
        "title": "title01"            
    },
    "2": {
        "id": 2,
        "title": "title02" 
    },
    ...

Resulting C# class should look like this

public class NewsResult
{
    public ICollection<News> Result { get; set; }
}

I have trouble to map this JSON to some C# object hierarchy automatically. Do you have any idea please how to resolve this problem? I would prefer C# code that I mentioned but I would try another approach if it will be needed. One more info: I can't change REST service. Thank you.

y0j0
  • 3,369
  • 5
  • 31
  • 52
  • 1
    Which JSON library are you using at the moment? – Jon Skeet May 21 '14 at 19:16
  • What does `NewsResult` look like? Further, what does the result look like *when it does work?* – Mike Perrenoud May 21 '14 at 19:16
  • 1
    That's because it can't be mapped to an object.`result` can be converted to a `Dictionary` or a `dynamic` – jgauffin May 21 '14 at 19:16
  • @Jon Skeet I don't use any JSON library. It works automatically according to this article : [Calling a Web API From a .NET Client](http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client) – y0j0 May 21 '14 at 19:19
  • You will have to use a custom `JsonConverter` which serializes/deserializes the `Result[]`. See the solution here that you can easily adapt to your situation: http://stackoverflow.com/a/17746239/325521 – Shiva May 21 '14 at 19:21
  • @jgauffin Thank you, you are right, Dictionary works correctly :) – y0j0 May 21 '14 at 19:26

1 Answers1

2

this should work

HttpClient c = new HttpClient();
var response = await c.GetAsync(yoururl);
var newsResult = await response.Content.ReadAsAsync<NewsResult>();

public class NewsResult
{
    public Dictionary<string, Item> result { set; get; }
}

public class Item
{
    public string id { set; get; }
    public string title { set; get; }
}
L.B
  • 114,136
  • 19
  • 178
  • 224