【问题标题】:Need to extract attribute and value(s) from json string需要从 json 字符串中提取属性和值
【发布时间】:2017-02-06 03:45:03
【问题描述】:

我有一个 Json 字符串,我反序列化并变成了一个有 2 个键的字典。我对它的值包含的键(服务)很感兴趣,其中包含一系列服务,每个服务都有自己的属性,都在一行中,由逗号和括号分隔。我希望能够遍历这些服务并获得每个服务的属性。我认为正则表达式会做到这一点,但我找不到匹配的模式 `

 responseDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(response);
 var services = responseDictionary["services"]

我取回的值有这个模式

"[\r\n  {\r\n    \"name\": \"extract\",\r\n    \"type\": \"FeatureServer\"\r\n  },\r\n  {\r\n    \"name\": \"extract\",\r\n    \"type\": \"MapServer\"\r\n  }\r\n]"

有2个服务,

extract---类型特征服务器。

extract---mapserver 类型

我该怎么做才能获得这两种服务类型?

【问题讨论】:

    标签: c# json regex string data-structures


    【解决方案1】:

    你的 JSON 格式化后的样子:

    [{
        "name": "extract",
        "type": "FeatureServer"
    },
    {
        "name": "extract",
        "type": "MapServer"
    }]
    

    并且可以映射到类:

    public class Service
    {
        public string name { get; set; }
        public string type { get; set; }
    }
    

    所以你可以像这样反序列化它:

    List<Service> services = JsonConvert.DeserializeObject<List<Service>>(response);
    

    并为每个服务循环:

    foreach(Service s in services)
    {
        string name = s.name;
        string type = s.type;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多