I miss a simple validation check in JSON.net

127 Views Asked by At

I get user input which I need to store in a database field of the JSON-type. This can be anything and may be anything as long as it is valid JSON. In JSON.net there is a way to validate JSON against a JSON scheme but that is too specific.

Now I have to deserialize the JSON string and use a try-catch for this and I rather do a simple:

JsonTextReader rJSonReader = new JsonTextReader(new StringReader(@sCellValue));
if (rJSonReader.isValid()) {#more code here;}

This would be much cleaner I think. Or am I wrong?

2

There are 2 best solutions below

0
On

Here is a library that encapsulates the complexity of parsing JSON objects, while allowing you the flexibility to validate its properties by simply reading from a NameValueCollection.

Subclass the Deserialiser<T> class and loop through the JSON properties in the NameValueCollection returned as a result of calling Deserialise() in your implementation. You can effectively introduce your own custom validation by determining whether or not each expected property is present in the collection:

class SimpleObjectDeserialiser : Deserialiser<SimpleObject> {
    public SimpleObjectDeserialiser(SimpleJSONParser parser) : base(parser) {}

    public override SimpleObject Deserialise() {
        var properties = parser.Parse();

        bool isValid;

        var expectedProperties = new List<string> {"name", "age"};
        if (expectedProperties.Any(expectedProperty => !properties.AllKeys.Contains(expectedProperty))) {
            isValid = false;
        }
        else {
            isValid = true;
        }

        if (isValid) {
            return new SimpleObject
            {
                Name = properties.Get("name"),
                Age = Convert.ToInt32(properties.Get("age"))
            };
        }
        else {
            throw new JSONValidationException();
        }           
    }
}

Leveraging this, you don't need to worry about parsing the JSON object, and can focus on validating the result instead. I'm happy to walk through this in more detail.

0
On

I'd suggest writing an extension method, analogous to TryParse for e.g. int. Do a try/catch inside, write to provided variable and return if the operation was succesful.

You could write your own Json syntax validator, but that seems like spending way to much time on a problem that is not really a problem :)