我有以下json,它采用geojson格式,并且Id希望能够将其解析为c#中的嵌套列表:
public IList<IList<IList<double>>> Coordinates { get; set; }
"coordinates": [
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]
我尝试了以下但是我得到了一个例外:
var node = jsonProperties["geometry"]["coordinates"].Values();
var coordinates = node.Select(x=>x.Value<List<double>>());
例外细节:
无法将Newtonsoft.Json.Linq.JArray转换为 Newtonsoft.Json.Linq.JToken。
答案 0 :(得分:2)
使用newtonsoft
反序列化。使用Foo
属性创建coordinates
类,使用大括号括起JSON脚本以将其表示为对象,然后调用JsonConvert.DeserializeObject<Foo>(Json)
。
private class Foo
{
public List<List<List<double>>> coordinates { get; set; }
}
var json = @"{
coordinates: [
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]
}";
var result = JsonConvert.DeserializeObject<Foo>(json);
答案 1 :(得分:1)
可能不是您想要的,但使用动态类型我可以访问这些值。例如,此示例代码
class Program
{
static void Main(string[] args)
{
string sampleJson = @"{ ""coordinates"": [
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]}";
dynamic d = JObject.Parse(sampleJson);
Console.WriteLine(d.coordinates[0].Count);
foreach (var coord in d.coordinates[0])
{
Console.WriteLine("{0}, {1}", coord[0], coord[1]);
}
Console.ReadLine();
}
显示以下内容:
5
-3.21333843172079, 55.9403825884992
-3.21334049048752, 55.9403818673503
-3.21334049048752, 55.9403818673503
-3.21381416622873, 55.9402150211751
-3.21413960035129, 55.9401008428437
答案 2 :(得分:1)
我建议您将它们解析为更合适的内容,例如List<Tuple<double, double>>
,尽管还有嵌套列表的解决方案。请查看我的内联评论:
const string json = @"
{
""coordinates"":
[
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]
}";
var jsObject = JObject.Parse(json);
/*
* 1. Read property "coordinates" of your root object
* 2. Take first element of array under "coordinates"
* 3. Select each pair-array and parse their values as doubles
* 4. Make a list of it
*/
var result = jsObject["coordinates"]
.First()
.Select(pair => new Tuple<double, double> (
pair[0].Value<double>(),
pair[1].Value<double>()
)
).ToList();
对于List<List<List<double>>>
,请参阅@YTAM回答。