I am trying to parse only part of provided JSON. I am using Newtonsoft.Json.Schema nuget. For the next example, I want to deserialize only name and age properties.
JSchema schema = JSchema.Parse(@"{
'id': 'person',
'type': 'object',
'additionalProperties' : false,
'properties': {
'name': {'type':'string'},
'age': {'type':'integer'}
}
}");
JsonTextReader reader = new JsonTextReader(new StringReader(@"{
'name': 'James',
'age': 29,
'salary': 9000.01,
'jobTitle': 'Junior Vice President'
}"));
JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader);
validatingReader.Schema = schema;
JsonSerializer serializer = new JsonSerializer();
JObject data = serializer.Deserialize<JObject>(validatingReader);
If I will set 'additionalProperties' : true
I will get unnecessary fields deserialized.
But if I will set 'additionalProperties' : false
, I will receive an error:
Newtonsoft.Json.Schema.JSchemaValidationException: Property 'salary' has not been defined and the schema does not allow additional properties. Path 'salary', line 4, position 11.
Note that I will know the needed fields only in runtime. I receive big JSON and I need to create some solution to deserialize only part of this JSON. And users should decide which properties should be processed and which aren't.