问题
We receive JSON data from Facebook Real Time subscription. The JSON itself contains property like "object":"page" and we need to access this property.
{
"entry":[
{
"changes":[ ],
"id":"1037501376337008",
"time":1465883784
}
],"object":"page"
}
We use dynamic object to parse the JSON but when we try to access the result.object, it is not allowed as object is the keyword in C#.
dynamic result = JsonConvert.DeserializeObject<dynamic>(jsonRealTimeNotification);
string objectType = result.object.ToString(); // This line does not build
We can replace the "object" by some text in the original JSON string and then parse but we are looking if there is a standard way to handle this
回答1:
Use @object
:
dynamic result = JsonConvert.DeserializeObject<dynamic>(jsonRealTimeNotification);
string objectType = result.@object.ToString();
This is the same syntax as is used when specifying a regular verbatim identifier. From the C# Language Specification, § 2.4.2 Identifiers (C#):
The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier.
Sample fiddle.
来源:https://stackoverflow.com/questions/38520406/json-how-to-parse-the-json-string-which-contains-objectpage