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.

6
  • 1
    Which JSON library are you using at the moment? Commented May 21, 2014 at 19:16
  • What does NewsResult look like? Further, what does the result look like when it does work? Commented May 21, 2014 at 19:16
  • 1
    That's because it can't be mapped to an object.result can be converted to a Dictionary<string, YourType> or a dynamic Commented May 21, 2014 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 Commented May 21, 2014 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: stackoverflow.com/a/17746239/325521 Commented May 21, 2014 at 19:21

1 Answer 1

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@YoYo: You can award LB the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.