2013-06-28 46 views
0

获取字符串列表我有了这个JSON(下),我无法选择串的名单,这将是“马里兰州”,“纽约”,“宾夕法尼亚州”。使用LINQ to从Json的

{ 
    "displayFieldName": "NAME", 
    "fieldAliases": { 
    "STATE": "STATE" 
    }, 
    "fields": [ 
    { 
     "name": "STATE", 
     "type": "esriFieldTypeString", 
     "alias": "STATE", 
     "length": 20 
    } 
    ], 
    "features": [ 
    { 
     "attributes": { 
     "STATE": "Maryland" 
     } 
    }, 
    { 
     "attributes": { 
     "STATE": "New York" 
     } 
    }, 
    { 
     "attributes": { 
     "STATE": "Pennsylvania" 
     } 
    } 
    ] 
} 

到目前为止,我得到了json字符串并将其反序列化为一个JObject,我可以看到这些孩子。我遇到了麻烦,但它不适合我见过的其他示例,因为“功能”是“属性”的集合。我在编写linq时遇到了麻烦,无法进入下一个阶段。

这里是我的代码:

  var foo = response.Content.ReadAsStringAsync().Result; 

      var json = (JObject)JsonConvert.DeserializeObject(foo); 

      var cf = json["features"].Children(); 

任何人可以帮助我的LINQ语句,从这个国家得到的字符串?

感谢

回答

0

假设你JObject类看起来莫名其妙地像下面的示例中,你可以做到以下几点:

string[] states = json.features.SelectMany(f => f.attributes).ToArray(); 

这就产生了与三个条目马里兰州,纽约州和宾夕法尼亚州的一个阵列。

全样本:

class JObject 
{ 
    public Feature[] Features { get; set; } 
} 

class Feature 
{ 
    public string[] Attributes { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Feature f1 = new Feature { Attributes = new[] { "Maryland" } }; 
     Feature f2 = new Feature { Attributes = new[] { "New York" } }; 
     Feature f3 = new Feature { Attributes = new[] { "Pennsylvania" } }; 

     JObject state = new JObject 
     { 
      Features = new[] { f1, f2, f3 } 
     }; 

     string[] states = state.Features.SelectMany(f => f.Attributes).ToArray(); 
    } 
} 
+0

感谢您的帮助。我按照你的建议使用SelectMany,并发布我的最终代码。 – chuck

+0

下面是代码(对不起,我不能看到如何使用代码风格的评论):
变种R = response.Content.ReadAsStringAsync()结果; var json =(JObject)JsonConvert.DeserializeObject(f); 。 变种arrayStates = JSON [ “特征”]的SelectMany(F => F [ “属性”])ToArray的(); 列表 lstStates =新列表(); 的foreach(在arrayStates VAR JT) { lstStates.Add(jt.First()的ToString()); } – chuck