2

I'm making webapi using .net core 2.2. And I'm new to .net framework So far I was working with javascript based frameworks like nodejs expressjs.

It's easy to customize JSON response in nodejs. Can you exaplain how to customize the JSON response with .NET Core 2.2 WebApi? Just point me to right direction.

Let me give an example,

C# User Model

public class User {
    int id {get;set;}
    string name {get;set;}
    string username {get;set;}
    string password {get;set;}
}

Default API Get Reponse.

public ActionResult<IEnumerable<User>> GetAll()

Json:

[
    {
        "id":1,
        "name": "John Doe",
        "username": "john",
        "password": "AH7B302Iapxf7EFzZVW0/kJDuf/I3pDPkQ42IxBTakA="
    },
    {   
        "id":2,
        "name": "Jane Doe",
        "username": "jane",
        "password": "AH7B302Iapxf7EFzZVW0/kJDuf/I3pDPkQ42IxBTakA="
    }
]

I need to customize the output like this.

{
    "statuscode": 200,
    "count"     : 2,
    "data"      : 

    [
        {
            "name": "John Doe",
            "username": "john",
        },
        {
            "name": "Jane Doe",
            "username": "jane",
        }
    ]
}
7
  • Do you mean dynamically shaping the response or always return it in the latter form? Commented Nov 27, 2018 at 12:03
  • how did you get this user data? could you please add that code also? Commented Nov 27, 2018 at 12:11
  • create a strongly type mode to represent the desired graph/envelope and return that Commented Nov 27, 2018 at 12:14
  • 1
    Why include the status code in the JSON response when you already have it in the HTTP response? Commented Nov 27, 2018 at 12:24
  • @KarelTamayo Yes, I need to dynamically shape the responses. Commented Nov 27, 2018 at 12:32

2 Answers 2

4

You can use anonymous objects, which comes in handy if you don't want to define a separate class for each and every result type:

public ActionResult<object> GetAll()
{
    var list = _userRepository.GetAll(); // <-- if this is not (yet) an Array or a List, then force single evaluation by adding .ToArray() or .ToList()
    var model = new
    {
        statuscode = 200,
        count = list.Count, // or .Length if list is an Array
        data = list.Select(x => new { name = x.name, username = x.userName })
    };
    return Ok(model);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Nice. This is exactly what I'm expecting. Thanks a lot.
Peter, I see that the shape of the response is defined in the controller method. Why should it be defined here? Can't the repository or service shape the response and return it so that the controller can just deliver it? I am under the impression that controllers should have the least logic possible.
3

I guess you are asking for a generic return object for your api, if it is so, you need to define a return object as follows,

Your return object model, as considering your all entities have a base type IEntity or a BaseEntity.

public class Result<T> where T: IEntity
{
    public int StatusCode { get; set; }
    public int Count { get; set; }
    public IEnumerable<T> Data { get; set; }
}

And a sample action method,

public IActionResult<IEnumerable<User>> GetAll()
{
    var list = _userRepository.GetAll();
    var model = new Result<User>
    {
        StatusCode = 200,
        Count = list.Count,
        Data = list
    };

    return Ok(model);
}

7 Comments

change the action return type or update the class to be derived from IEnumerable<User>
Yes, This is what I'm asking. Do I have to define classes for each custom JSON responses?
This will still output all 4 fields for each User object, instead of just user + username.
@ibubi Thanks this is also helpful.
ibubi, I see that the shape of the response is defined in the controller method. Why should it be defined here? Can't the repository or service shape the response and return it so that the controller can just deliver it? I am under the impression that controllers should have the least logic possible.
|

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.