Parsing Multidimensional JSON Array with Newtonsoft Json.NET

前端 未结 1 1426
梦毁少年i
梦毁少年i 2021-02-06 18:08

I have Json returning as the following:

[{\"CreatedBy\":\"GIS_DB\",\"CreatedDate\":\"3/8/2012 10:44:00 AM\",\"Id\":39,\"ModifiedBy\":\"\",\"ModifiedDate

相关标签:
1条回答
  • 2021-02-06 18:29

    Instead of declaring a lot of classes, I would parse the json string as follows

    JArray jArr = (JArray)JsonConvert.DeserializeObject(jsonstr);
    foreach (var item in jArr)
    {
        foreach(var subitem in item["TrailCoordinates"])
        {
            Console.WriteLine(subitem["Longitude"] + " " + subitem["Latitude"]);
        }
    }
    

    If monotouch supports dynamic you can also write

    dynamic jArr2 = JsonConvert.DeserializeObject(jsonstr);
    foreach (dynamic item in jArr2)
    {
        foreach (var subitem in item.TrailCoordinates)
        {
            Console.WriteLine(subitem.Longitude + " " + subitem.Latitude);
        }
    }
    

    You can even use Linq

    JArray jArr = (JArray)JsonConvert.DeserializeObject(jsonstr);
    var coords = jArr
                .Select(x => x["TrailCoordinates"])
                .SelectMany(x=>x)
                .Where(x => x["TrailId"].ToString() == "40")
                .Select(x => new { Lat = double.Parse(x["Latitude"].ToString()), Lon=double.Parse(x["Longitude"].ToString()) })
                .ToArray();
    
    0 讨论(0)
提交回复
热议问题