简体   繁体   中英

How to retrive json string from Url in Xamarin.forms pcl

For example I have an URL http://www.pizzaboy.de/app/pizzaboy.json As WebClient is not supported in Xamarin.forms PCL, I went with Xamarin documentation of using web services in forms and followed this example.

Link

I have tried all what I can do to get the json string. But it's not working.

Below code doesn't work for mentioned URL

public async Task<List<TodoItem>> RefreshDataAsync ()
        {
        var uri = new Uri ("http://www.pizzaboy.de/app/pizzaboy.json");
        HttpClient myClient = new HttpClient();
    
            var response = await myClient.GetAsync (uri);
if (response.IsSuccessStatusCode) {
                    var content = await response.Content.ReadAsStringAsync ();
                    Items = JsonConvert.DeserializeObject <List<TodoItem>> (content);
                }
}

Response comes with content set to null .

[Disclaimer: It was network proxy issue which was blocking the above url, above code is just fine]

Your snippet looked all OK to me and I just gave it a try and it worked like charm for me. I got JSON string in content variable and I could deserialize it also. Here am sharing the snippet I used.

public static async Task RefreshDataAsync ()
    {
        var uri = new Uri ("http://www.pizzaboy.de/app/pizzaboy.json");
        HttpClient myClient = new HttpClient();

        var response = await myClient.GetAsync (uri);
        if (response.IsSuccessStatusCode) {
            var content = await response.Content.ReadAsStringAsync ();
            var Items = JsonConvert.DeserializeObject <List<RootObject>> (content);
            Console.WriteLine ("");
        }
    }

Here is my definition for the class RootObject I used

public class RootObject
{
    public string Name { get; set; }
    public string Address1 { get; set; }
    public int Zip { get; set; }
    public string City { get; set; }
    public string Phone { get; set; }
    public double Lat { get; set; }
    public double Lon { get; set; }
    public string Link { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM