user603007
user603007

Reputation: 11794

json validation not working?

I am trying to validate my json through schemavalidation but I think there are some issues:

string schemaJson = @"
{
    'description': 'A payload',
    'type': 'object',
    'properties': {
        'totalRecords': {'type':'number'},
        'payload': {
            'type': 'object',
            'properties': {'name':{'type':'string'}}
        }
    },
    'additionalProperties': false
}";

JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject payl = JObject.Parse(@"
{
    'totalRecords': 75,
    'payload':{'namdse':'ksjfkjsdkfjkd'}
}");

IList<string> messages;
bool valid = payl.IsValid(schema, out messages);

Console.WriteLine(valid);

foreach (string message in messages)
{
    Console.WriteLine(message);
}

The console returns true but it should return false because I am using the wrong property name namdse instead of name.

Upvotes: 1

Views: 1437

Answers (2)

IronGeek
IronGeek

Reputation: 4883

Try setting the additionalProperties to false in your payload properties.

...
'payload': {
  'type': 'object',
  'properties': {
    'name':{'type':'string'}        
  },
  'additionalProperties': false
}
...

Your json is valid because namdse is being considered as additional property. And if name is a required field, you might need to add the required keyword also.

...
'payload': {
  'type': 'object',
  'properties': {
    'name':{'type':'string', 'required': true}        
  },
  'additionalProperties': false
}
...

Upvotes: 3

fuzzybear
fuzzybear

Reputation: 2405

Your Object is invalid json, use double quotes, this is valid in http://jsonlint.com/

{
"description": "A payload",
"type": "object",
"properties": {
    "totalRecords": {
        "type": 123
    },
    "payload": {
        "type": "object",
        "properties": {
            "name": {
                "type": "string"
            }
        }
    }
},
"additionalProperties": false
}

Upvotes: 0

Related Questions