JSON:如何解析包含"object"的JSON字符串: [英] JSON: How to parse the JSON string which contains "object":"page"

查看:462
本文介绍了JSON:如何解析包含"object"的JSON字符串:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们从Facebook实时订阅中接收JSON数据. JSON本身包含诸如"object":"page"之类的属性,我们需要访问此属性.

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"
}

我们使用动态对象来解析JSON,但是当我们尝试访问result.object时,由于object是C#中的关键字,因此它是不允许的.

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

我们可以用原始JSON字符串中的某些文本替换对象",然后进行解析,但是我们正在寻找是否有标准的方法来处理此问题

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

推荐答案

使用@object:

dynamic result = JsonConvert.DeserializeObject<dynamic>(jsonRealTimeNotification);
string objectType = result.@object.ToString();    

这与指定常规 verbatim标识符时使用的语法相同.从 C#语言规范,第2.4.2节标识符(C#):

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.

示例小提琴.

这篇关于JSON:如何解析包含"object"的JSON字符串:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆