JSON API is a specification for how a client should request that resources be fetched or modified, and how a server should respond to those requests.
JSON API is designed to minimize both the number of requests and the amount of data transmitted between clients and servers. This efficiency is achieved without compromising readability, flexibility, or discoverability.
The current version of JSON API is 1.0. and will always be backward compatible. And JSON API requires the use of the JSON API media type application/vnd.api+jsonfor exchanging data.
- services.AddJsonApi<AppDbContext>();
- public class ArticlesController : JsonApiController<Article>
- {
- public ArticlesController(
- IJsonApiContext jsonApiContext,
- IResourceService<Article> resourceService)
- : base(jsonApiContext, resourceService) { }
- }
- Class Customer{
- public string FirstName {get; set;}
- public string LastName {get; set;}
- }
- // Also There were doing un-necessary implemenation to make first letter in the attribute make Uppercase.
- // eg:- URL:- /api/articles?filter[firstname]=sam
- private List<FilterQuery> ParseFilterQuery(string key, string value)
- {
- var queries = new List<FilterQuery>();
- var propertyName = key.Split('[', ']')[1].ToProperCase();
- }
- // Atribute name look like FirstName, once they apply Propercase method
- var concreteType = typeof(TSource);
- var property = concreteType.GetProperty(filterQuery.FilteredAttribute.InternalAttributeName);
- if (property == null)
- throw new ArgumentException($"'{filterQuery.FilteredAttribute.InternalAttributeName}' is not a valid property of '{concreteType}'");
- // here it will throw you the exception because it is not able to find the Attribute name, hence your sending filter with lower case
-
- Install-Package VisionPlanner.JsonAPI -Version 1.1.1
- services.AddJsonApi(opt =>
- {
- opt.Namespace = "api/v1";
- opt.DefaultPageSize = 5;
- opt.IncludeTotalRecordCount = true;
- });
- public class JsonAPISuccessController : Controller
- {
- private readonly IJsonoutputService _jsonoutputService;
- public JsonAPISuccessController(IJsonoutputService jsonoutputService)
- {
- _jsonoutputService = jsonoutputService;
- }
- }
- public class ModelService
- {
- private readonly IJsonoutputService _jsonoutputService;
- public ModelService(IJsonoutputService jsonoutputService)
- {
- _jsonoutputService = jsonoutputService;
- }
- }
- private int getTotalItems<TSource>(Expression expressions)
- {
- var usersCount = expressions != null ? MockingUserDetails().AsQueryable().Where(expressions.ToString()).ToList().Count() : MockingUserDetails().AsQueryable().ToList().Count();
- return usersCount;
- }
- public JsonParseObject getParseObject()
- {
- var oblDetails = _jsonoutputService.GetFilterExpression<UserDetails>();
- oblDetails.TotalCount = getTotalItems<UserDetails>(oblDetails.Expression);
- return oblDetails;
- }
- public List<UserDetails> getUserDetails<TSource>(JsonParseObject parseObject)
- {
- var query = parseObject.Expression != null ? MockingUserDetails().AsQueryable().Where(parseObject.Expression.ToString()).ToList() :
- MockingUserDetails().AsQueryable().ToList();
- if (parseObject.SortQueries != null)
- {
- var orderedEntities = query.AsQueryable().Sort(parseObject.SortQueries[0]);
- if (parseObject.SortQueries.Count() > 1)
- {
- for (var i = 1; i < parseObject.SortQueries.Count(); i++)
- orderedEntities = orderedEntities.Sort(parseObject.SortQueries[i]);
- }
- if (orderedEntities != null)
- query = orderedEntities.ToList();
- }
- var results = query.Skip(parseObject.pageSize * (parseObject.pageNumber - 1))
- .Take(parseObject.pageSize);
- return results.ToList();
- }
"using Visionplanner.JsonAPI.Repository;"
- [HttpGet, Route("userdetails")]
- [ProducesResponseType((int)HttpStatusCode.OK)]
- [ProducesResponseType((int)HttpStatusCode.NotFound)]
- public IActionResult GetUserDetails()
- {
- var details = _modelService.getParseObject(); // it will return JsonParseobject with Filter/Sort/Paging
- var userDetails = _modelService.getUserDetails<UserDetails>(details); // it will retuern processed data
- var results = _jsonoutputService.GetParsingData<UserDetails>(userDetails.AsQueryable(), details.pageSize, details.pageNumber, details.TotalCount); // it will return seralize data.
- if (results.Data.Count() > 0)
- return new ObjectResult("SuccessCode") { StatusCode = 200 };
- else
- return new ObjectResult("NotApplicable") { StatusCode = 406 };
- }
- The method will prepare jsonParseobject (inside we have Expression built based on the url and sorting parameters and paging parameters)
- This is the actual method that will return data from the service layer.
- This method is the JSON library method to transform data and prepare the JSON object.
- {
- "links": [
- {
- "href": "http://localhost:59312/api/v1.0/Contact/tenantid/76E23186-D637-46E3-9D07-845DD928D3B6?page[size]=5&page[number]=1",
- "rel": "first",
- "method": "GET"
- }
- ],
- "meta": {
- "total-records": 1
- },
- "data": {
- "data": [
- {
- "type": "userviewmodel",
- "id": "2e2d946b-9874-4e97-b732-a97000b74513",
- "attributes": {
- "firstName": "krishna",
- "lastName": "jaya",
- "initial": "k",
- "gender": "Male",
- "email": "[email protected]",
- "optedOut": "Yes",
- "linekedHomePage": "www.google.com",
- "phone": "1234567890",
- "attachment": "Nothing",
- "roles": [
- {
- "roleName": "DecisionMaker"
- }
- ],
- "notes": "Testing User",
- "contactType": "UserContact",
- "status": "Active",
- "salutation": "MR",
- "tenantId": "76e23186-d637-46e3-9d07-845dd928d3b6"
- }
- }
- ]
- }
- }

Mokarom HossainPosted Dec 31, 2020, 10:37 AM
Hi thanks for this nice article. While experimenting I am getting the following error - 'Unable to resolve service for type 'Visionplanner.JsonAPI.Repository.IJsonoutputService' while attempting to activate 'TestJsonApi.Controllers.PersonsController'.'. Tried to add 'services.AddSingleton<IJsonoutputService, JsonoutputService>();' in my startup with no success. Can you please include what should be added in the Stratup.cs file to make this work?
Jayakrishna KPosted Nov 29, 2018, 12:49 AM
Just now i have release new version 2.0.0 to supported .Net Framework 4.7.1 and .NetCore 2.0.0