thefid
thefid

Reputation: 177

Object is not populated with the JSON data when deserialized with NewtonSoft

    using Telerik.Newtonsoft.Json;

MVC Controller:

    public ActionResult Index()
    {
        string responseStr = GetJSON();
        var jObject = JsonConvert.DeserializeObject<TheViewModel>(responseStr);

        if (jObject == null)
        {
            return Content("");
        }

        return View("Default", jObject);
    }

Temporary hard coded JSON method:

    public string GetJSON() //to be replaced after testing
    {
        string json = @"{
        'name': 'Trial 11.7',
        'id': 2599,
        'version': '11.7',
        'product_id': '1040',
        'time_of_execution': '2017-08-07T22:15:38.000Z',
        'site_url': 'http://something.com/',
        'mc_gem': '11.7',
        'suite_gem': '11.7',
        'passing_percentage': 95.65,
        'failing_percentage': 4.35
        }";

        return json;
    }

The model:

public class TheViewModel
{
    public class RootObject
    {
        public string name { get; set; }
        public int id { get; set; }
        public string version { get; set; }
        public string product_id { get; set; }
        public string time_of_execution { get; set; }
        public string site_url { get; set; }
        public string mc_gem { get; set; }
        public string suite_gem { get; set; }
    }
}

The problem is that I get the following as the value when I step through the code:

    jObject {Master.Project.Mvc.Models.TheViewModel}    Master.Project.Mvc.Models.TheViewModel

For some reason I am not getting the JSON deserialized into the object. It is probably something simple, but I am not seeing it.

I receive no error message to help determine the issue inside the controller.

Any help would be appreciated.

Upvotes: 0

Views: 535

Answers (2)

Jayee
Jayee

Reputation: 562

Refactor your code, extract the 'RootObject' class to its own file (or move it so that it is not defined under a class.) will solve the problem.

Upvotes: 1

Bpendragon
Bpendragon

Reputation: 44

You're trying to convert the JSON to an object of type TheViewModel when it's looking for a type of RootObject

You can fix this by either moving all of the fields in RootObject out and into TheViewModel or by calling ...DeserializeObject<TheViewMode.RootObject>(respon‌​seStr);

Upvotes: 2

Related Questions