2017-04-04 126 views
1

沒有某些數據我有一個JSON如下: JSON錯誤當JSON

在上述JSON,第一數據具有「IMAGE_URL」的數據,而第二數據沒有「IMAGE_URL」的數據。

JSON用於gridview。我有一個問題,那就是:如果你沒有對JSON的「圖片網址」的數據,這將是如下錯誤:

Error Message

XAML:

<GridView 
       x:Name="itemGridView" Grid.Row="1" 
       AutomationProperties.AutomationId="ItemDetailScrollViewer" 
       Margin="10,5,0,0" HorizontalAlignment="Center" 
       SelectionMode="None" 
       IsSwipeEnabled="false" 
       IsItemClickEnabled="True" 
       ItemClick="itemGridView_ItemClick" 
       DataContext="{Binding SelectedItem, ElementName=itemListView}" 
       ScrollViewer.HorizontalScrollMode="Auto" ScrollViewer.VerticalScrollMode="Auto" 
       ScrollViewer.ZoomMode="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto"> 

       <GridView.ItemTemplate> 
        <DataTemplate> 
         <Grid Height="300" Width="215" Margin="10,10,0,0" Background="{x:Null}" BorderBrush="#FF646464" BorderThickness="0.5"> 
          <Grid.RowDefinitions> 
           <RowDefinition Height="auto"/> 
           <RowDefinition Height="*"/> 
          </Grid.RowDefinitions> 

          <Border x:Name="coverBox" Grid.Row="0" Margin="10,10,0,0" Width="190" Height="150" VerticalAlignment="Top" HorizontalAlignment="Left" BorderBrush="{x:Null}" BorderThickness="0.5"> 
           <Border.Background> 
            <ImageBrush Stretch="UniformToFill" ImageSource="images/IP-placeholder.png"/> 
           </Border.Background> 
           <Image x:Name="cover" Source="{Binding ImageURL}" HorizontalAlignment="Center" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" ImageOpened="Image_ImageOpened" Loaded="cover_Loaded" Loading="cover_Loading" DataContextChanged="cover_DataContextChanged"/> 
          </Border> 

          <StackPanel Grid.Row="1" Margin="0,5,0,0"> 
           <TextBlock x:Name="id" Text="{Binding ID}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="Wrap" Foreground="#FF8D8D8D" FontSize="17" Margin="0,0,0,0" FontWeight="SemiBold" Visibility="Collapsed"/> 
           <StackPanel Height="25" Background="{x:Null}"> 
            <TextBlock x:Name="title" Margin="10,0,0,0" Text="{Binding Title}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap" Foreground="Black" FontSize="15" FontWeight="Normal" /> 
           </StackPanel> 
           <TextBlock x:Name="rating" Margin="10,5,10,0" Text="{Binding Rating}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="Wrap" Foreground="#FF8D8D8D" FontSize="17" FontWeight="SemiBold"/> 
           <StackPanel Margin="10,5,10,0" Height="40"> 
            <TextBlock x:Name="address" Text="{Binding Address}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="Wrap" Foreground="Black" FontSize="14" FontWeight="SemiLight"/> 
           </StackPanel> 
           <TextBlock x:Name="phones" Margin="10,5,0,0" Text="{Binding Phone}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="Wrap" Foreground="#FFD47A22" FontSize="14"/> 
          </StackPanel> 
         </Grid> 
        </DataTemplate> 
       </GridView.ItemTemplate> 
      </GridView> 

代碼:

try 
         { 
          loading.Visibility = Visibility.Visible; 
          string urlPath1 = "http://.../results.json?module=listing&page=2&token=3f63-dc43-c8d5-eb45-8cbf-b72d-9d98-800f"; 
          var httpClient1 = new HttpClient(new HttpClientHandler()); 

          var values1 = new List<KeyValuePair<string, string>> 
          { 

          }; 
          HttpResponseMessage response1 = await httpClient1.GetAsync(urlPath1); 
          response1.EnsureSuccessStatusCode(); 

          if (!response1.IsSuccessStatusCode) 
          { 
           busyIndicator.IsActive = false; 
           RequestException(); 
          } 
          string jsonText1 = await response1.Content.ReadAsStringAsync(); 
          JsonObject jsonObject1 = JsonObject.Parse(jsonText1); 
          JsonArray jsonData1 = jsonObject1["data"].GetArray(); 

          foreach (JsonValue groupValue1 in jsonData1) 
          { 
           JsonObject groupObject2 = groupValue1.GetObject(); 

           double id = groupObject2["id"].GetNumber(); 
           string title = groupObject2["title"].GetString(); 
           string address = groupObject2["address"].GetString(); 
           string phone = groupObject2["phone"].GetString(); 
           double rating = groupObject2["rating"].GetNumber(); 
           string image_url = groupObject2["image_url"].GetString(); 

           ListingClass file1 = new ListingClass(); 
           file1.ID = Convert.ToInt32(id); 
           file1.Title = title; 
           file1.Address = address; 
           file1.Phone = phone; 
           file1.Rating = Convert.ToInt32(rating); 
           file1.ImageURL = image_url; 

           listingDatasource.Add(file1); 
          } 
          itemGridView.ItemsSource = listingDatasource; 
          busyIndicator.IsActive = false; 
         } 

         catch (HttpRequestException ex) 
         { 
          busyIndicator.IsActive = false; 
          RequestException(); 
         } 

我想如果沒有「image_url」數據,圖像不顯示(只有邊框)。 如何處理?

+0

爲什麼不直接將JSON字符串反序列化到'ListingClass'類的集合?這會將缺失屬性的值設置爲默認值。 –

+0

我使用ListingClass在gridview上顯示。如何修復代碼? – Rose

+0

我已經發布了下面的答案。如果您可以分享您正在處理的實際JSON的一部分,我可以提供更好的一個。 –

回答

1

如果你想要一個簡單的異常解決方案,你可以檢查JsonObject是否有鍵,並且與鍵關聯的值是否爲空,並將圖像url設置爲string.Empty如果爲空,如下所示。

string image_url = groupObject2.ContainsKey("image_url") && groupObject2["image_url"] != null ? groupObject2["image_url"].GetString() : string.Empty; 

否則,您可以使用以下代碼將JSON反序列化爲ListingClass的集合。

您必須添加對Nuget包「Newtonsoft.Json」的引用才能使此代碼正常工作。

//Other code of calling service.. 
string jsonText1 = await response1.Content.ReadAsStringAsync(); 

var jsonObj = JObject.Parse(jsonText1); 

var data = jsonObj["data"].ToString(); 

var listingDatasource = JsonConvert.DeserializeObject<List<ListingClass>>(data); 

itemGridView.ItemsSource = listingDatasource; 
busyIndicator.IsActive = false; 
+0

我無法安裝Newtonsoft.Json並顯示錯誤消息:https://drive.google.com/file/d/0B4oRSWSS0hKDOW56cHpBSzgyakU/view?usp=sharing – Rose

+0

您如何安裝?這是一個nuget包.....你分享的錯誤信息並沒有太多有關錯誤原因的信息。 –

+0

如果您使用Newtonsoft.Json變得太複雜,我剛纔在我的答案中提供了一個簡單的解決方案。請參考它。 –