Method ParseJToken
ParseJToken(string)
Safely parses a JSON string into a Newtonsoft.Json.Linq.JToken while enforcing a maximum depth limit to protect against excessively nested or potentially malicious JSON structures.
Declaration
public static JToken ParseJToken(string json)
Parameters
Type | Name | Description |
---|---|---|
string | json | The JSON string to parse into a Newtonsoft.Json.Linq.JToken. |
Returns
Type | Description |
---|---|
JToken | A Newtonsoft.Json.Linq.JToken representing the root of the parsed JSON structure. The result may be a Newtonsoft.Json.Linq.JObject, Newtonsoft.Json.Linq.JArray, or any other supported token type depending on the input. |
Remarks
This method uses Newtonsoft.Json.JsonTextReader internally with a strict maximum depth defined by MaxDepth to prevent stack overflows or memory exhaustion from deeply nested input. It's particularly useful when consuming external or user-supplied data that may be untrusted.
Usage of this method provides enhanced safety compared to directly calling Parse(string), which does not impose a depth limit by default.
Example:
var token = Utils.ParseJToken(jsonString);
var config = token["settings"]?["theme"]?.Value<string>();
Exceptions
Type | Condition |
---|---|
ArgumentNullException | Thrown if the |
JsonReaderException | Thrown if the JSON is malformed or exceeds the configured maximum depth (MaxDepth). |