1

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();
}
3
  • 1
    Is that firstItem public? Commented Oct 30, 2020 at 16:31
  • Please attach class ItemVM code too. Commented Oct 30, 2020 at 16:33
  • @evk You are correct. Please post that as an answer. LOL Very simple mistake, but worth noting. Commented Oct 30, 2020 at 16:36

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

OR ItemVM.firstItem is variable and not public property

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.