【问题标题】:C# Searching for a property and returning its value in Newtonsoft JSON.NetC# 在 Newtonsoft JSON.Net 中搜索属性并返回其值
【发布时间】:2018-02-14 13:17:05
【问题描述】:

我无法将数据序列化为 C# 对象,因为同一组对象的 JSON 结构不同。是否有某种函数可以让您搜索所有 JSON 属性及其子属性以返回您搜索的属性的值?

我通过 API 接收的数据示例(我正在尝试返回属性“propertyIamLookingFor”的值):

第一个例子

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "propertyIamLookingFor": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    }
}} 

第二个例子

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "propertyIamLookingFor": 32
}}

第三个例子

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "height": 500,
            "propertyIamLookingFor": 11
        }
    }
}} 

请注意,无论其位置如何,该属性始终具有相同的名称,因此我知道该属性的名称并尝试返回该值。

*如果有人想知道,这是我正在访问的一个糟糕的 API,但没有选择不使用它的选项。

【问题讨论】:

  • 该函数假定您熟悉该值,但我并不熟悉,它实际上可以是任何东西,因为它们是我正在尝试阅读的消息。我正在寻找一个函数,您可以在其中输入属性名称并取回该属性的值,但无论 JSON 结构中的属性位置如何,因为它的位置是完全可变的。
  • 如果没有你收到的数据类型的例子,我会在黑暗中射击试图在这里回答你。
  • @DanielleSummers 这里是例子
  • 那么找到该属性的规则是什么?姓名?你可以enumerate json找到它。

标签: c# json properties json.net


【解决方案1】:

您可以为此使用 JSONPath,它类似于 XPath。

例如,要查找所有名为 myProp 的属性,请使用 JSONPath 表达式

$..myProp

这是一个递归选择器,将迭代所有属性和子道具等。

JSONPath 内置于 json.net 库中

再看看http://newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm,但要深入挖掘:)

【讨论】:

  • 将尝试使用 $.. 并让您知道 :)
  • 有效!谢谢!
【解决方案2】:

我没有设法在 JSON.Net 中找到一个函数来查找属性(无论在 JSON 结构中的位置)并返回其值,但 XmlDocument.GetElementsByTagName 与 XML 配合得很好。所以我只是使用 JsonConvert.DeserializeXmlNode 将 JSON 转换为 XML,然后使用 XmlDocument.GetElementsByTagName 来查找我的属性。希望它可以帮助遇到相同问题的其他人,并希望其他人发布一个更简单的方法来实现这一点。

编辑:Charleh 设法在 JSON 中指出了方法,被接受为最佳答案

【讨论】:

  • 像我之前说的那样使用 jsonpath。转到此处jsonpath.com 并将搜索表达式更改为$..type 作为示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2014-02-15
  • 2023-01-27
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多