I don't know if I have done this correctly or not, but I have the following class to try to validate and parse JSON:
public static class JsonHelper
{
internal const string UserResetDataScheme = @"{
'title' : 'UserResetDataModel',
'type' : 'object',
'properties': {
'Role' : {'type' : 'integer'},
'Email' : {'type' : 'string'},
},
required: [ 'Role', 'Email']
}";
internal static T TryParseJson<T>(this string json, string schema) where T : new()
{
var parsedSchema = JSchema.Parse(schema);
var jObject = JObject.Parse(json);
return jObject.IsValid(parsedSchema) ? JsonConvert.DeserializeObject<T>(json) : default(T);
}
}
Most of the time the schema check works fine, but sometimes I need to deserialize a string like this:
"\"User sent null or empty data\""
In that case the schema validation should return false. However, I get an error when I call JObject.Parse:
Newtonsoft.Json.JsonReaderException: 'Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '',
I am using the schema which I have shown above.
If I understand this right, I can't parse to string? But then what do I do in this case? How can I validate the JSON is incorrect if I can't parse it?
(JSON which conforms to this schema parses correctly.)
"\"User sent null or empty data\""