VeryVicious VeryVicious - 1 month ago 6
JSON Question

Can't populate list with deserialized JSON in ASP.NET

I am writing an app with ASP.NET MVC 4 and I try to populate list inside object of my type. I wrote console app just to try this code out:

using (var webClient = new WebClient())
var json = webClient.DownloadString(URL);
var myTypeVariable= new JavaScriptSerializer().Deserialize<MyTypeSummary>(json);
return myTypeVariable;

myTypeVariable is an object of type:

public class MyTypeSummary
public int Id { get; set; }
public List<MyType> MyTypeItems{ get; set; }
public DateTime PublicationDate { get; set; }

Unfortunatelly when I used this code in ASP.NET Index() action it got only DateTime property populated properly. The MyTypeItems Listremained null, just opposite to the effect of executing this in my console application(List was properly populated).

My class looks like this:

public class MyType
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public int Unit { get; set; }
public double Price1{ get; set; }
public double Price2{ get; set; }
public double Price3{ get; set; }

And I can't figure out why in console app this worked well and in asp isn't working at all. Can anyone help?
Edit: this is the json string I am getting:

"{\"publicationDate\":\"2016-09-23T11:36:26.4723947Z\",\"items\":[{\"name\":\"US Dollar\",\"code\":\"USD\",\"unit\":1,\"purchasePrice\":3.6682,\"sellPrice\":3.6779,\"averagePrice\":3.6730},{\"name\":\"Euro\",\"code\":\"EUR\",\"unit\":1,\"purchasePrice\":3.8842,\"sellPrice\":3.9027,\"averagePrice\":3.8935},{\"name\":\"Swiss Franc\",\"code\":\"CHF\",\"unit\":1,\"purchasePrice\":3.7940,\"sellPrice\":3.8041,\"averagePrice\":3.7990},{\"name\":\"Russian ruble\",\"code\":\"RUB\",\"unit\":100,\"purchasePrice\":6.8865,\"sellPrice\":6.9096,\"averagePrice\":6.8981},{\"name\":\"Czech koruna\",\"code\":\"CZK\",\"unit\":100,\"purchasePrice\":13.9250,\"sellPrice\":13.9584,\"averagePrice\":13.9417},{\"name\":\"Pound sterling\",\"code\":\"GBP\",\"unit\":1,\"purchasePrice\":5.6786,\"sellPrice\":5.6989,\"averagePrice\":5.6887}]}"


Your class should be like this as per the JSON you provided. You can try converting your JSON to object at Json2Csharp.

 public class Item
        public string name { get; set; }
        public string code { get; set; }
        public int unit { get; set; }
        public double purchasePrice { get; set; }
        public double sellPrice { get; set; }
        public double averagePrice { get; set; }

    public class MyTypeSummary
        public string publicationDate { get; set; }
        public List<Item> items { get; set; }