Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate JSON object?

I would like to validate incoming json object for correctness at the server side. Is there a standard / optimal way to do that? What is your approach of validation?

like image 623
Harsha Hulageri Avatar asked Feb 26 '23 00:02

Harsha Hulageri


1 Answers

My advice - deserialize the JSON and see if it breaks. For example, if you're using C# on the server side, you can use the newfangled DataContractJsonSerializer, or do it the old way with the JavaScriptSerializer which is arguably much simpler.

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<Dictionary<string, object>>(jsonString);

EDIT: And now that it's come out that you're using Java, of course my C# example is not going to work for you, but the concept is the same. Stackoverflow already has some answers here: Convert a JSON string to object in Java ME?

like image 163
mattmc3 Avatar answered Mar 04 '23 03:03

mattmc3