I can create JObject
var jobject = Newtonsoft.Json.Linq.JObject.Parse(jsonstring);
I want to convert the jobject read only so that no new keys can be added or existing values modified.
I can create JObject
var jobject = Newtonsoft.Json.Linq.JObject.Parse(jsonstring);
I want to convert the jobject read only so that no new keys can be added or existing values modified.
It can't be done. There is an open issue for implementing it:
https://github.com/JamesNK/Newtonsoft.Json/issues/468
But it is two years old and has drawn very little attention as far as I can tell.
An immutable object is one that can't be changed. If you don't want consumers of your JObject to change it, just give them a copy. (Note: this example uses the abstract superclass JToken
of JObject
to provide a more general solution.)
private JToken data = JToken.Parse(@"{""Some"":""JSON""}");
public JToken Data()
{
return data.DeepClone();
}
public JToken Data(string path)
{
return data.SelectToken(path).DeepClone();
}
The consumer will be able to change their copy, but not the source.
If data
is so large that cloning it is prohibitive, use the second method JToken Data(string path)
to grab a subset.