Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check JSON and XML is valid? c#

Im using newtonsoft json.net http://json.codeplex.com/ and I would like to know ...

how to validate json and xml are valid json/xml.

how do i verify this?

like image 716
001 Avatar asked Jan 07 '12 02:01

001


2 Answers

Where you want to validate json, on server side or on client side. Assuming you want to do it on server side, try deserializing the json string. if it breaks, then its not a valid json. Use JavaScriptSerializer for deserializing purpose

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<Dictionary<string, object>>(json);
like image 94
Anand Avatar answered Sep 24 '22 19:09

Anand


If you are using the JSON.net software, you could do exactly as Anand stated. Simply deserialize the JSON string and if it breaks or errors out, then it is not a valid JSON structure. Now, if you're trying to do something like http://jsonlint.com/ then you are probably reaching beyond the scope of what we could help you out with on the forums. If you wanted to check if it errors out or not, simply use the following code in C# where result is the JSON string:

var root = JsonConvert.DeserializeObject<RootObject>(result);

where the information you want to deserialize from the JSON string would have to have a class of RootObject that is similar to:

public class RootObject
{
    // You would need to create items here to store each of the objects' information in the JSON file.
    // For example:
    public string itemName { get; set; }
    public int itemID { get; set; }
}

Now, this is assuming that you know the information that SHOULD be in the JSON file. Otherwise, that's a whole program in and of itself.

like image 43
th3n3wguy Avatar answered Sep 26 '22 19:09

th3n3wguy