QFDev
QFDev

Reputation: 9008

Test for valid JSON in .NET

Is there a way in .NET that I can test if a JSON string I am about to send back to the client is valid? I am using an ASHX handler that accepts a bunch of form variables and returns a chunk of JSON that gets interpreted by the client. One of the parameters in the JSON contains a block of html that despite encoding sometimes gets corrupted with characters that cause a JSON error on the client. I'd like to catch this before it goes and email the sys admin with the details.

Additional info:

Target Framework 4.0

.ajax JQuery method used to send and read the response.

Upvotes: 0

Views: 143

Answers (3)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

You could try to deserialize it using the DataContractJsonSerializer class.

Upvotes: 0

Viktor Elofsson
Viktor Elofsson

Reputation: 1601

Well, one idea is to try deserializing it server side (with your JSON framework of choice, be it Newtonsoft.Json or JsonFx) before sending it to the client.

Upvotes: 1

snurre
snurre

Reputation: 3105

I would use Json.NET and have something like JObject.Parse(json) in a try/catch block

Upvotes: 0

Related Questions