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.
jobject? Would C# public variable as writeable inside the class but readonly outside the class be of use to you?jobjectinstance. Or are you saying that all instances of JObject must be read-only?JObject.PropertyChangingandJContainer.ListChanged, but the latter happens after the change, so it's too late.