Skip to main content
 首页 » 编程设计

c#之如何使用 newtonsoft json 解析 3 级嵌套数组

2024年02月06日13lhb25

我有以下 json,它是 geojson 格式,我希望能够将其解析为 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>>()); 

异常详情:

Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken.

请您参考如下方法:

反序列化使用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);