【问题标题】:JSON.NET - Getting nested valuesJSON.NET - 获取嵌套值
【发布时间】:2017-07-17 16:25:50
【问题描述】:

我有一个类似这样的 JSON:

  {
    "key": "Target",
    "value": {
      "__type": "Entity:http://schemas.microsoft.com/xrm/2011/Contracts",
      "Attributes": [
        {
          "key": "prioritycode",
          "value": {
            "__type": "OptionSetValue:http://schemas.microsoft.com/xrm/2011/Contracts",
            "Value": 1
          }
        },
        {
          "key": "completeinternalreview",
          "value": false
        },
        {
          "key": "stepname",
          "value": "10-Lead"
        },
        {
          "key": "createdby",
          "value": {
            "__type": "EntityReference:http://schemas.microsoft.com/xrm/2011/Contracts",
            "Id": "ca2ead0c-8786-e511-80f9-3863bb347b18",
            "KeyAttributes": [],
            "LogicalName": "systemuser",
            "Name": null,
            "RowVersion": null
          }
        }
      ]
    }
  }

如何通过搜索key的值来获取key/value?

例如我想得到键值对'completeinternalreview'

【问题讨论】:

  • 反序列化 JSON 字符串后,您将拥有一个带有 value.Attributes 的对象,您可以在该对象上执行简单的 LINQ 查询。

标签: json.net


【解决方案1】:

假设您有一个像这样的 C# 类来表示 JSON 中的属性对象:

public class MyValue
{
    [JsonProperty("Attributes")]
    public List<KeyValuePair<string, object>> Attributes { get; set; }
}

你可以简单地反序列化字符串:

var result = JsonConvert.DeserializeObject<KeyValuePair<string, MyValue>>(jsonString);

然后找到正确的键值对:

var kvp = result.Value.Attributes.Find(a => a.Value == "completeinternalreview");

【讨论】:

  • 非常好,正是我需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
相关资源
最近更新 更多