Warm tip: This article is reproduced from stackoverflow.com, please click
c# xamarin xamarin.forms

Photo loading from URL in JSON file in Xamarin.Forms

发布于 2020-04-07 10:13:42

I'm trying to load photo from link which is in JSON file. I am deserializing the JSON from the link and I bind the link to an Image Source like this:

<Image HorizontalOptions="Center" Source="" x:Name="foto" 
    WidthRequest="200" HeightRequest="200"/>

This is my code behind:

foto.Source = Zdjecie;

Zdjecie is the value in JSON file which looks like this:

[
  {
    "Nazwa": "Czekolada mleczna Sport & Fitness",
    "Opis": "Przykładowy opis produktu Czekolada mleczna Sport & Fitness",
    "Zdjecie": "https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg",
    "WW": 0.28,
    "WBT": 0.22,
    "Energia": 31.8125,
    "Tluszcz": 2.19375,
    "Weglowodany": 3.225,
    "Blonnik": 0.11875,
    "Bialko": 0.45625,
    "Zelazo": 0.1875,
    "Wapn": 15.5
  },
  {
    "Nazwa": "Czekolada mleczna Sport & Fitness2",
    "Opis": "Przykładowy opis produktu Czekolada mleczna Sport & Fitness2",
    "Zdjecie": "https://kif.pl/www/wp-content/uploads/2015/05/chocolate_PNG27-620x413.png",
    "WW": 0.16,
    "WBT": 0.21,
    "Energia": 28.5625,
    "Tluszcz": 2.19375,
    "Weglowodany": 2.94375,
    "Blonnik": 0.4875,
    "Bialko": 0.34375,
    "Zelazo": 0.8125,
    "Wapn": 0
  }
]

I think everything is fine but none of the photos are loading I also tried using:

foto.Source = new UriImageSource()
{
    img = new Uri(Zdjecie);
}

but this doesn't work either.

Questioner
user9604562
Viewed
70
Jack Hua - MSFT 2020-02-03 16:58

You should add a breakpoint in the line foto.Source = Zdjecie; to see if you have get the correct value of Zdjecie. I wrote a simple demo and it works on my sided, you can check below codes:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        string jsonStr = "[{'Nazwa': 'Czekolada mleczna Sport & Fitness','Opis': 'Przykładowy opis produktu Czekolada mleczna Sport & Fitness', 'Zdjecie': 'https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg'}]";

        var ObjContactList = JsonConvert.DeserializeObject<List<RootObject>>(jsonStr);

        RootObject obj = ObjContactList[0];

        foto.Source = obj.Zdjecie;
    }
}

public class RootObject
{
    public string Nazwa { get; set; }
    public string Opis { get; set; }
    public string Zdjecie { get; set; }
}

And in Xaml:

<StackLayout>
    <!-- Place new controls here -->
    <Button Clicked="Button_Clicked" Text="Click to load the Image" 
       HorizontalOptions="Center"
        />

    <Image HorizontalOptions="Center" Source="" x:Name="foto" 
WidthRequest="200" HeightRequest="200"/>
</StackLayout>