3

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.

5
  • 1
    What is the scope of jobject? Would C# public variable as writeable inside the class but readonly outside the class be of use to you? Commented Oct 28, 2015 at 18:37
  • @AndrewMorton I do not control the JObject class. I can write a wrapper around it but it will not be trivial. Commented Oct 28, 2015 at 18:40
  • 1
    You don't need to alter the JObject class, rather, just control the access to that jobject instance. Or are you saying that all instances of JObject must be read-only? Commented Oct 28, 2015 at 18:50
  • @AndrewMorton not all but I do not understand how to control access without writing a wrapper class. Commented Oct 28, 2015 at 18:53
  • You can throw an exception in JObject.PropertyChanging and JContainer.ListChanged, but the latter happens after the change, so it's too late. Commented Oct 28, 2015 at 19:05

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.