简体   繁体   中英

JObject contains a C# keyword - how to access it?

I am using the JQuery QueryBuilder plugin on my site, which compiles it's data into JSON. On the server side code, I take the JSON that is returned from the plugin and parse it into a dynamic variable. The problem is, one of the keys is "operator", and the word operator is ac# keyword. I've tried using _operator, __operator, but these do not work. Any idea how I can access the value of the key "operator"?

For example, here is the JSON that I am working with (simplified, of course):

[{
     "id":"ABC",
     "value":"test",
     "operator":"equal"
}]

And here is the server side C# code

dynamic json = JObject.Parse(model.pJson);
foreach (var item in json.rules) {
     string id = item.id;    
     string value = item.value;
     string _operator = item.operator; // HERE IS THE PROBLEM! I cannot type item.operator because operator is a keyword
}

You can use @ to use a keyword as an identifier, so this should work:

string _operator = item.@operator;

Alternatively, you may well find that indexer access would be fine:

string _operator = item["operator"];

尝试将item["operator"]用作字典。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM