使用Linq从Json获取字符串列表
我得到了这个JSON(如下),我在选择字符串列表时遇到了问题,这些字符串可能是“马里兰”、“纽约”、“宾夕法尼亚” 到目前为止,我正在获取json字符串并将其反序列化到JObject,我可以看到子对象。不过,我很难更进一步地理解它,因为“特性”是“属性”的集合,所以它不适合我看到的其他示例。我在写linq以进入下一个层次时遇到了困难 这是我的密码:使用Linq从Json获取字符串列表,json,linq,c#-4.0,json.net,esri,Json,Linq,C# 4.0,Json.net,Esri,我得到了这个JSON(如下),我在选择字符串列表时遇到了问题,这些字符串可能是“马里兰”、“纽约”、“宾夕法尼亚” 到目前为止,我正在获取json字符串并将其反序列化到JObject,我可以看到子对象。不过,我很难更进一步地理解它,因为“特性”是“属性”的集合,所以它不适合我看到的其他示例。我在写linq以进入下一个层次时遇到了困难 这是我的密码: var foo = response.Content.ReadAsStringAsync().Result;
var foo = response.Content.ReadAsStringAsync().Result;
var json = (JObject)JsonConvert.DeserializeObject(foo);
var cf = json["features"].Children();
有人能帮我用linq语句从中得到一系列状态吗
谢谢假设您的
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();
}
}
谢谢你的帮助。我正在使用您推荐的SelectMany,并将发布我的最终代码。以下是代码(抱歉,我看不到如何使用代码样式进行注释):var r=response.Content.ReadAsStringAsync().Result;var json=(JObject)JsonConvert.DeserializeObject(f);var arrayStates=json[“features”]。SelectMany(f=>f[“attributes”])。ToArray();List lstStates=新列表();foreach(arrayStates中的var jt){lstStates.Add(jt.First().ToString());}
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();
}
}