Explain JSON and how to add JSON Patch To Your ASP.Net Core Project
JSON
- The new built-in JSON support, System.Text.Json, is high-performance, low allocation, and based on Span<byte>.
- The System.Text.Json namespace provides high-performance, low allocating, and standards-compliant capabilities to process JavaScript Object Notation (JSON), which includes serializing objects to JSON text and deserializing JSON text to objects, with UTF-8 support built-in.
- It also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM) for random access of the JSON elements within a structured view of the data.
- Run Package Manager and install JSON Patch Library with the command:
Install-package Microsoft.AspNetCore. JsonPatch Write in your controller public class Person
[ (public string FirstName (get; set;)
public string LastName (get;set;)) ]
[Route ("api/ [controller]")]
public class PersonController: Controller (
private readonly Person _default Person =newPerson
FirstName="Jim",
LastName="Smith"
};
[HttpPatch ("update") ]
public Person Patch ( [FromBody] JsonPatchDocument<Person> personPatch) {
personPatch.ApplyTo(_defaultPerson);
return defaultPerson;
}
}
- In the above example, we are just using a simple object stored on the controller and updating that, but in a real API, we will be pulling the data from a data source, applying the patch, then saving it back.
- When we call this endpoint with the following payload:
[{"op":"replace", "path": "FirstName", "value": "Bob"}]
- We get the response of :
{"firstName": "Bob", "lastName": "Smith"}
first name got changed to Bob!
Comments
Post a Comment