I have a raw string. I just want to validate whether the string is valid JSON or not. I'm using JSON.NET.
C# – How to make sure that string is valid JSON using JSON.NET
cjson.net
Related Topic
- C# – How to convert JSON to XML or XML to JSON
- C# – How to convert UTF-8 byte[] to string
- C# – Get property value from string using reflection
- Json – How to deserialize JSON to a simple Dictionary
in ASP.NET - C# – JavaScriptSerializer – JSON serialization of enum as string
- C# – How to turn a C# object into a JSON string in .NET
- C# – How to ignore a property in class if null, using json.net
- C# – How to change property names when serializing with Json.net
Best Answer
Through Code:
Your best bet is to use parse inside a
try-catch
and catch exception in case of failed parsing. (I am not aware of anyTryParse
method).(Using JSON.Net)
Simplest way would be to
Parse
the string usingJToken.Parse
, and also to check if the string starts with{
or[
and ends with}
or]
respectively (added from this answer):The reason to add checks for
{
or[
etc was based on the fact thatJToken.Parse
would parse the values such as"1234"
or"'a string'"
as a valid token. The other option could be to use bothJObject.Parse
andJArray.Parse
in parsing and see if anyone of them succeeds, but I believe checking for{}
and[]
should be easier. (Thanks @RhinoDevel for pointing it out)Without JSON.Net
You can utilize .Net framework 4.5 System.Json namespace ,like:
(But, you have to install
System.Json
through Nuget package manager using command:PM> Install-Package System.Json -Version 4.0.20126.16343
on Package Manager Console) (taken from here)Non-Code way:
Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is: