JSON: How to parse the JSON string which contains “object”:“page”

别来无恙 提交于 2019-12-31 05:28:12

问题


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

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