Skip to main content
 首页 » 编程设计

c#之使用 Newtonsoft 的 JSON.NET 在 C# 中处理名为 "private"的 JSON 对象的属性

2024年02月13日14webabcd

我正在尝试解析从 xively 返回的 json 字符串来自 Air Quality Egg .其中一个属性说明 xively 提要是公共(public)的还是私有(private)的。该属性称为 private 并采用字符串值“true”或“false”。为了从提要中获取数据,我调用 xively 的 Historical Data成功返回有效 JSON 的 REST API。然后我使用 JSON.NET 在 C# 中解析 JSON。我的解析是这样开始的:

dynamic historicalDatapoints  = JValue.Parse(jsonString) as JObject; 
if (historicalDatapoints != null) 
{ 
    var id = historicalDatapoints.id; 
    var title = historicalDatapoints.title.ToString(); 
    var privacy = bool.Parse(historicalDatapoints.private.ToString()) 
    // More parsing 
} 

我对最后一行代码有疑问。 C# 不允许我引用名为“private”的属性。这是相应的(编辑过的)JSON:

{ 
    "id": 000000843, 
    "title": "Blah Road Egg 02", 
    "private": "false", 
    //... 
} 

使用 JSON.NET 我应该如何解析属性 private?

请您参考如下方法:

尝试 historicalDatapoints.@private 访问该值。如果这不起作用,那么您也可以尝试 historicalDatapoints["private"]