How to make Newtonsoft.Json.Linq.JObject immutable?

爱⌒轻易说出口 提交于 2019-12-23 16:01:05

问题


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.


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/33398889/how-to-make-newtonsoft-json-linq-jobject-immutable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!