I have a huge JSON schema with a part of it looking like this:
{
"if":{
"required":[
"product_category"
],
"properties":{
"product_category":{
"contains":{
"required":[
"value"
],
"properties":{
"value":{
"enum":[
"20005000"
]
}
}
}
}
}
},
"then":{
"properties":{
"product_subcategory":{
"items":{
"properties":{
"value":{
"enum":[
"20005085",
"20005088",
"20005065",
"20005068",
"20005401",
"20005115",
"20005118",
"20005010",
"20005505",
"20005105",
"20005108",
"20005135"
]
}
}
}
}
}
},
"else":{
"if":{
"required":[
"product_category"
],
"properties":{
"product_category":{
"contains":{
"required":[
"value"
],
"properties":{
"value":{
"enum":[
"20055000"
]
}
}
}
}
}
},
"then":{
"properties":{
"product_subcategory":{
"items":{
"properties":{
"value":{
"enum":[
"20055005",
"20055010",
"20055015",
"20055020",
"20055040",
"20055045",
"20055050",
"20055075",
"20055085",
"20055090",
"20055095",
"20055100",
"20055110"
]
}
}
}
}
}
},
"else":{
"if":{
"required":[
"product_category"
],
"properties":{
"product_category":{
"contains":{
"required":[
"value"
],
"properties":{
"value":{
"enum":[
"20056000"
]
}
}
}
}
}
},
"then":{
"properties":{
"product_subcategory":{
"items":{
"properties":{
"value":{
"enum":[
"20056010",
"20056005",
"20056050",
"20056020",
"20056025",
"20056100",
"20056070",
"20056090",
"20056040",
"20056035",
"20056030"
]
}
}
}
},
"else":{
"if":"more nested if-then-else here"
}
}
}
}
}
}
I want to call JSchema.Load() on it. The problem is that depth of that JSON exceeds default MaxDepth = 64 and Load() method throws Newtonsoft.Json.JsonReaderExceptio. My code looks like this:
using (var stringReader = new StringReader(json))
using (var jsonReader = new JsonTextReader(stringReader))
{
var schema = JSchema.Load(jsonReader);
}
I’ve tried to set JsonTextReader.MaxDepth to 256 but then I get StackOverflowException.
I wrote custom JsonTextReader implementation which shouldn’t go deeper after reaching maxDepth:
class DepthLimitingJsonReader : JsonTextReader
{
private readonly int _maxDepth;
private int _currentDepth;
public DepthLimitingJsonReader(TextReader reader, int maxDepth)
: base(reader)
{
_maxDepth = maxDepth;
_currentDepth = 0;
}
public override bool Read()
{
bool result = base.Read();
if (result)
{
if (TokenType == JsonToken.StartObject || TokenType == JsonToken.StartArray)
{
_currentDepth++;
// If depth exceeds maxDepth, skip the content inside this object or array
if (_currentDepth > _maxDepth && Path.EndsWith("else"))
{
Skip();
}
}
else if (TokenType == JsonToken.EndObject || TokenType == JsonToken.EndArray)
{
_currentDepth--;
}
}
return result;
}
}
But anyway Skip() method process tokens deeply within the structure and still exceptions are thrown. I want ignore everything what is deeper than maxDepth. How can I do that?
1