How to Validate JSON on Server Side

jsonvalidationweb-development

I'm working on Web Application (ASP.Net MVC) that will allow users to edit a JSON object in the browser and save it to database.

To do so, JSON object will be sent from view to server side (controller) and will be converted to entities (C# objects). At that moment, I can perform server side validation. After that, entities are converted back to JSON and saved to database.

I understand the necessity of server side validation, but I'm not happy with converting JSON to C# entities and back to JSON.

Is this a proper way to do server side validation?
If not, How can I properly validate and save JSON object from client to server?

Best Answer

JSON object will be sent from view to server-side (controller) and will be converted to entities (C# objects). At that moment, I can perform server-side validation. After that, entities are converted back to JSON [...]

I understand the necessity of server-side validation, but I'm not happy with converting JSON to C# entities and back to JSON.

Indeed, deserializing JSON strings to objects just for validating the content can be overkill. Overall, if we end up serializing them back to JSON (well, we don't need to serialize them again since we already have the original JSON).

Is this a proper way to do server-side validation?

Quoting @Christopher

Yes, this is a proper way to do validation - nothing is inherently wrong with the operation... But here are some other options if you want to improve performance and still maintain the current functionality

JSON Schemas

JSON schemas allow you to validate the JSON format (model) and several constraints like not nulls, required fields, matching patterns, etc. If your library is customizable, probably you will be allowed to extend the validations process so that, you can add new constraints (rather related to the business). If you are familiar with XML, JSON Schemas and XSD are homologous.

JSONPath

In addition to JSON Schemas we have JsonPath1 for querying JSON strings without having to map JSONs to specific data models. Well, at least not to one we have to care about. If you need a programmatic approach (in contrast with declarative, as JSON Schemas use to be), JsonPath should do the job.

In any case, both are not mutually exclusive.


1: This is pretty much the same idea of XPath

Related Topic