Reputation: 127
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",
}
]
}
Upvotes: 2
Views: 3085
Reputation: 2539
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);
}
Upvotes: 3
Reputation: 24137
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);
}
Upvotes: 4