C# get Image Url from JSON response
本问题已经有最佳答案,请猛点这里访问。
我正在编写一个C应用程序,它应该从JSON获取事件数据。
假设我的JSON响应如下,我如何从响应中得到
另外,如何下载图像并在图像控件中显示它?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | { "total_items":"24", "page_number":"1", "page_size":"10", "page_count":"3", "events": { "event": [ { "url":"<event-1-url>", "id":"event-1", "city_name":"Seattle", "description":"car show event", "image": { <-- THIS COULD BE NULL, HOW TO HANDLE NULL VALUE? "thumb": { "width":"32", "url":"<image_url>/carshow.jpg", "height":"32" } }, "date":"2015-12-09 13:20:20", "owners": { <-- THIS COULD BE NULL OR MULTIPLE OWNERS, HOW TO GET ALL OWNERS NAMES? "owner": [ { "name":"John Doe", "id":"O12", "bio":"fast track racer" }, { "name":"Tom Tomasson", "id":"O513", "bio":"fines collector" } ] }, }, { "url":"<event-2-url>", "id":"event-2", "city_name":"Blaine", "description":"toyota event", "image": null, <-- NO IMAGE IS PROVIDED "date":"2015-12-09 13:20:20", "owners": null, <-- NO OWNER IS PROVIDED }, {...} ] } } |
谢谢
您可以这样使用newtonsoft json:
1 2 3 4 5 6 7 8 9 10 11 | dynamic deserializedJson = JsonConvert.DeserializeObject(yourJson); foreach(dynamic car in deserializedJson.cars.car) { string url = car.image.thumb.url; string img = url.Split(new string[] {"/" }, StringSplitOptions.RemoveEmptyEntries)[1]; using (WebClient client = new WebClient()) { client.DownloadFile(url, img); } } |
号
可以使用newtonsoft.json中的linq to json从json获取URL。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | string stringJson = @"{ ""total_items"":""24"", ""page_number"":""1"", ""page_size"":""10"", ""page_count"":""3"", ""cars"": { ""car"": [ { ""url"":""<honda-1-url>"", ""id"":""honda-1"", ""city_name"":""Seattle"", ""description"":""black Honda"", ""image"": { ""thumb"": { ""width"":""32"", ""url"":""<image_url>/honda1.jpg"", ""height"":""32"" } }, ""date"":""2015-12-09 13:20:20"" }, { ""url"":""<honda-2-url>"", ""id"":""honda-2"", ""city_name"":""Blaine"", ""description"":""red Honda"", ""image"": { ""thumb"": { ""width"":""32"", ""url"":""<image_url>/honda2.jpg"", ""height"":""32"" } }, ""date"":""2015-12-09 13:20:20"" } ] }}"; dynamic dynamicCars = JsonConvert.DeserializeObject(stringJson); foreach (dynamic car in dynamicCars.cars.car) { string url = car.image.thumb.url; } |