So simple yet I know not why it fails. In a WebAPI 2.0 ASP.NET MVC (pre-core) controller method, I have this:
[Route("GetItem")]
[HttpGet]
public ItemVM GetItem() {
var item = new ItemVM(); // Constructor initializes
return item;
}
When I run the code, the debugger shows this in item:
item {ViewModels.ItemVMs.ItemVM}
firstItem {ViewModels.ItemVMs.FirstItemVM}
id 0
archived false
name null
Yet WebAPI returns only this:
{}
I have tried suggestions like Newtonsoft json serializer returns empty object but Visual Studio 2017 says CreateProperties
does not exist to override.
Any help would be much appreciated.
EDIT:
LOL I told you it is a simple answer. Here's the class:
public class ItemVM {
FirstItemVM firstItem { get; set; }
public ItemVM() {
this.firstItem = FirstItemVM.ToMap( new Entities.Item());
}
}
public class FirstItemVM {
public int id { get; set; }
public bool archived { get; set; }
public string name { get; set; }
public static readonly Expression<Func<Entities.FirstItem, FirstItemVM>>
Map (e) => new FirstItemVM {
id = e.id,
archived = e.archived,
name = e.name
};
public static readonly Func<Entities.FirstItem, FirstItemVM>
ToMap = FirstItemVM.Map.Compile();
}
Most likely ItemVM.firstItem
is not public (for example, internal), and JSON serializer will only serialize public properties by default (unless you non-public property explicitly to be serialized).