Filtering Out Properties in an ASP.NET Core API

后端 未结 1 788
时光说笑
时光说笑 2021-01-18 14:22

I want to serve up the following JSON in my API:

{
  \"id\": 1
  \"name\": \"Muhammad Rehan Saeed\",
  \"phone\": \"123456789\",
  \"address\": {
    \"addre         


        
相关标签:
1条回答
  • 2021-01-18 15:02

    You can use dynamic with ExpandoObject to create a dynamic object containing the properties you need. ExpandoObject is what a dynamic keyword uses under the hood, which allows adding and removing properties/methods dynamically at runtime.

    [HttpGet("test")]
    public IActionResult Test()
    {
        dynamic person = new System.Dynamic.ExpandoObject();
    
        var personDictionary = (IDictionary<string, object>)person;
        personDictionary.Add("Name", "Muhammad Rehan Saeed");
    
        dynamic address = new System.Dynamic.ExpandoObject();
        var addressDictionary = (IDictionary<string, object>)address;
        addressDictionary.Add("PostCode", "AB1 2CD");
    
        personDictionary.Add("Address", address);
    
        return Json(person);
    }
    

    This results in

    {"Name":"Muhammad Rehan Saeed","Address":{"PostCode":"AB1 2CD"}}
    

    You'd just need to create a service/converter or something similar that will use reflection to loop through your input type and only carry over the properties you specify.

    0 讨论(0)
提交回复
热议问题