【问题标题】:compare key.name to a string of a json response将 key.name 与 json 响应的字符串进行比较
【发布时间】:2018-01-24 10:31:56
【问题描述】:

我有以下 json:

{
    "value": [
        {
            "id": "/subscriptions/5a9c0639-4045-4c23-8418-fc091e8d1e31/resourceGroups/citrix-xd-0ec69105-c451-4676-8723-97932bf4d94a-ayjzs",
            "name": "citrix-xd-0ec69105-c451-4676-8723-97932bf4d94a-ayjzs",
            "location": "australiaeast",
            "tags": {
                "CitrixResource": "Internal",
                "CitrixSchemaVersion": "2.0",
                "CitrixProvisioningSchemeId": "0ec69105-c451-4676-8723-97932bf4d94a",
                "BillTo": "O1001396_8796-SS-Citrix",
                "Reference Name": "Citrix POC"
            },
            "properties": {
                "provisioningState": "Succeeded"
            }
        }
]

注意:上面的 json 只是一个大 json 数组的一部分

我想读取特定的“标签”节点并比较“键名”,例如CitrixResource 到一个字符串并说如果它不一样然后失败。

到目前为止,我已经完成了以下工作:

JObject jsonParsed = JObject.Parse(result);
result = jsonParsed["value"].ToString()
var Response = JsonConvert.DeserializeObject<List<AzureResponse>>(result);
foreach (var AzureResponse in Response)
{
    //do something

    //and say
    {
        if (Tags.citrixResource.Propertyname = "name")
        {
            then pass;
        }
    }
}

【问题讨论】:

  • 您是否有任何标签(FooResource、CiscoNotResource 等),或者您是否尝试查看已设置的特定标签。这是两个完全不同的东西
  • 基本上我想读取所有节点名称“标签”并检查子值,因为这里它是“CitrixResource”,并与一个字符串比较“引用名称”,因为它们都不是同样应该失败。

标签: c# json key-value


【解决方案1】:

反序列化 json result

  var jsonParsed = JsonConvert.DeserializeObject<dynamic>(result);

json内的属性value转换为List&lt;AzureResponse&gt;

  //if the json is an object with `value` as property inside it
  var result = jsonParsed["value"].ToString();

  //if the `value` is an array of format `List<AzureResponse>`
  List<AzureResponse> AzureResponseList= new List<AzureResponse>();
  JsonConvert.PopulateObject(result, AzureResponseList);

使用Linq queries 循环遍历列表

  //then using `linq` we could query according to our needs
  var tag=AzureResponseList.Where(x=>x.tags['CitrixResource']=='name').FirstOrDefault();

或者使用foreach循环遍历列表

//example with foreach
foreach(var response in AzureResponseList){
   if(response.tags['CitrixResource']=='name'){
     //do something
   }
}

如果我们不想转换成任何模型,我们可以直接使用jsonParsed动态对象

  //without converting to some models we could directly use the jsonParsed 
  foreach(var response in jsonParsed ){
     if(response.tags['CitrixResource']=='name'){
         //do something
     }
  }

【讨论】:

  • 嗨,谢谢你,他们有什么方法可以循环运行它并比较所有子键,而不是我想说的“CitrixResource”tags.firstchild.PropertyName?有可能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
  • 2019-01-22
  • 1970-01-01
相关资源
最近更新 更多