decoder
decoder

Reputation: 926

Deserialize json array in web api project

My controller method is as follows

public ActionResult Index()
{
    Tweets model = null;
    var client = new HttpClient();
    var task = client.GetAsync("http://localhost:33615/api/product").ContinueWith((t) =>
    {
        var response = t.Result;
        var readtask = response.Content.ReadAsAsync<Tweets>();
        readtask.Wait();
        model = readtask.Result;
    });
    task.Wait();
    return View(model.Result);
}

The url return the row as follws:

[{"Id":1,"Name":"Honda Civic","Description":"Luxury Model 2013"},{"Id":2,"Name":"Honda Accord","Description":"Deluxe Model 2012"},{"Id":3,"Name":"BMW V6","Description":"V6 Engine Luxury 2013"},{"Id":4,"Name":"Audi A8","Description":"V8 Engine 2013"},{"Id":5,"Name":"Mercedes M3","Description":"Basic Model 2013"}]

My Tweets and tweet class are as follows:

public class Tweets
{
    public Tweet[] Result;
}
public class Tweet
{
    [JsonProperty("Name")]
    public string Name { get; set; }
    [JsonProperty("Description")]
    public string Description { get; set; }
}

I can't figure it out where i do mistake.it gives me following error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RestFiddlerTest.Controllers.Tweets' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly

How to fix this.

Upvotes: 1

Views: 6913

Answers (2)

decoder
decoder

Reputation: 926

I used Newtonsoft.Json.

public ActionResult Index()
    {
        List<Tweet> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://localhost:33615/api/product").ContinueWith((t) =>
        {
            var response = t.Result;
            var readtask = response.Content.ReadAsAsync<List<Tweet>>();
            readtask.Wait();
            model = readtask.Result;
        });
        task.Wait();
        return View(model);
    }

Upvotes: 2

Complexity
Complexity

Reputation: 5820

I've double checked your code and there are a few issues with it. First of all, I don't see your logic to deserialize to Json, according to the JSon object, I'm guessing that you're using Newtonsoft.Json?

Then you have a class Tweets which contains an array of Tweet objects. Now, when you create a small sample, like the following:

var dataToSerialize = new Tweets();
dataToSerialize.Result = new [] { new Tweet { Description = "Desc", Name = "Name" } };
var data = JsonConvert.SerializeObject(dataToSerialize);

The output of this piece of code will be the following:

{"Result":[{"Id":null,"Name":"Name","Description":"Desc"}]}

This is not the same as the output you get from your WebAPI.

Now, when you do use Newtonsoft.Json, when serializing your object, you are probably doing something like this:

const string JSon = "[{\"Id\":1,\"Name\":\"Honda Civic\",\"Description\":\"Luxury Model 2013\"},{\"Id\":2,\"Name\":\"Honda Accord\",\"Description\":\"Deluxe Model 2012\"},{\"Id\":3,\"Name\":\"BMW V6\",\"Description\":\"V6 Engine Luxury 2013\"},{\"Id\":4,\"Name\":\"Audi A8\",\"Description\":\"V8 Engine 2013\"},{\"Id\":5,\"Name\":\"Mercedes M3\",\"Description\":\"Basic Model 2013\"}]";
var data = JsonConvert.DeserializeObject<Tweets>(JSon);

Note: I've put the Json string in a string because I didn't have the time to write a full WebAPI.

Now, this will not work, because the string I input and that's also the one that your controller does return is not a Tweets object (remember you're missing the Result in your JSon string? Instead, this is a array of Tweet objects, so you can change your code like the following:

var data = JsonConvert.DeserializeObject<Tweet>(JSon);

Unfortunately, you will receive the exact same error. So why is that? Because you're trying to deserialize your object into an object of type Tweet while your object is an array of type Tweet.

So, modify your code like the following:

var data = JsonConvert.DeserializeObject<Tweet[]>(JSon);

Now, you're deserializing your object into the correct type.

enter image description here

So, I do hope that this post will help you.

Kind regards,

Upvotes: 2

Related Questions