Is there a way to validate a JSON structure against a JSON schema for that structure? I have looked and found JSON.Net validate but this does not do what I want.
JSO
Ok i hope this will help.
This is your schema:
public class test
{
public string Name { get; set; }
public string ID { get; set; }
}
This is your validator:
///
/// extension that validates if Json string is copmplient to TSchema.
///
/// schema
/// json string
/// is valid?
public static bool IsJsonValid(this string value)
where TSchema : new()
{
bool res = true;
//this is a .net object look for it in msdn
JavaScriptSerializer ser = new JavaScriptSerializer();
//first serialize the string to object.
var obj = ser.Deserialize(value);
//get all properties of schema object
var properties = typeof(TSchema).GetProperties();
//iterate on all properties and test.
foreach (PropertyInfo info in properties)
{
// i went on if null value then json string isnt schema complient but you can do what ever test you like her.
var valueOfProp = obj.GetType().GetProperty(info.Name).GetValue(obj, null);
if (valueOfProp == null)
res = false;
}
return res;
}
And how to use is:
string json = "{Name:'blabla',ID:'1'}";
bool res = json.IsJsonValid();
If you have any question please ask, hope this helps, please take into consideration that this isn't a complete code without exception handling and such...