How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. While the provided code snippet was helpful for working with XML asynchronously in a list box, I am looking to achieve the same functionality but with JSON data.

Below is the portion of code I used to retrieve data from a URL:

private void FlickrSearch_Click(object sender, RoutedEventArgs e)
    { 
      WebClient webclient = new WebClient(); 
      webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted); 
      webclient.DownloadStringAsync(new Uri("http://api.flickr.com/services/feeds/photos_public.gne?tag=" + SearchBox.Text + "&format=rss2")); // Flickr search 
  }

If anyone could provide guidance on handling JSON from a URL in a Windows Phone application, it would be greatly appreciated.

Answer №1

It seems like the scope of this question is quite broad for a detailed answer. However, assuming that you have already successfully implemented XML data based on the guidelines provided in the blog post mentioned above, making adjustments to work with JSON should not be too difficult.

  1. Begin by Installing Json.Net from NuGet Package Manager
  2. Examine the JSON format returned by the API by visiting the API search URL in your browser. Make sure to change the format specification to JSON, for instance, . You will notice that the returned JSON string is not valid and may require some manual cleanup to rectify this issue: remove "jsonFlickrFeed(" at the beginning and ")" at the end of the JSON string. After making these adjustments, the string will be ready for deserialization using Json.Net.
  3. The remaining steps should align with the instructions provided in the original blog post

Below is a code snippet illustrating the process of handling JSON data:

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
{ 
   if (e.Error != null)
    { 
       MessageBox.Show("error");
       return;
    } 

    var jsonString = e.Result;

    //clean up the JSON string to ensure its validity
    jsonString = jsonString.Replace("jsonFlickrFeed(", "");
    jsonString = jsonString.Remove(jsonString.Length - 1);

    //deserialize the JSON string into an object
    var rootObject = JsonConvert.DeserializeObject<JObject>(jsonString);
    var items = (JArray)rootObject["items"];

    //populate a listbox with items extracted from the JSON
    listBox1.ItemsSource = from tweet in items                                     
    select new FlickrData                                   
     { 
       ImageSource = tweet["media"]["m"].ToString(), 
       Message = tweet["description"].ToString(), 
       UserName = tweet["title"].ToString(), 
       PubDate = DateTime.Parse(tweet["published"].ToString())                                    
     };                 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Body section CSS selector

Can a CSS selector be included within the body section of an HTML document? Here's an example of my code (although it is not functioning as expected): <html> <head> </head> <body> <div style= "a[target=_blank] {backgroun ...

Execute javascript code 1.6 seconds following the most recent key release

Is there a more efficient way to execute JS 1.6 after a keyup event, considering that the timer should reset if another keyup event occurs within 1.6 seconds? One possible approach could involve utilizing a flag variable like this: var waiting = false; $ ...

Revamping the login interface for enhanced user

Whenever I attempt to login by clicking the login button, there seems to be an issue as it does not redirect me to any other page. Instead, I am left on the same page where I initially clicked the button. The intended behavior is for users to be redirected ...

In the React js and emotion framework, fonts are only loaded in production mode after the page has been re

I have set up emotion's Global component to globally apply a font to my app: export const GlobalStyle: FC<{}> = () => ( <Global styles={css` @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;50 ...

Implementing the insertion of a <div> element within an input field using jQuery

<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></scr ...

What is the best way to navigate through a complex array in React that includes objects and nested arrays?

I have been working on a JavaScript array that includes subobjects with arrays nested in them. My goal is to iterate through the entire parent object using React. Although I attempted the following approach, unfortunately it did not yield the desired outco ...

Manipulating strings dynamically in .NET within a conditional statement

I am facing an issue using a dynamic string in an if condition, as it is throwing an exception. var params = {}; params.windowKey = "File"; This 'params' variable is passed to another function for later use like this: escape(Ext. ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in ever ...

Access to property 'nodeType' on AJAX request in Firefox has been denied due to permission error

On my webpage, I have integrated the Google Sign-in button along with gapi for interaction. After a successful authentication using the Google API, an AJAX call is made to the server using JQuery: var token = gapi.auth.getToken(); var data = { "to ...

When placed within a setInterval loop, the event.clientY variable becomes inaccessible

I am working on a script to move an element around a web page, and I have encountered a problem. Whenever I try to put it in a loop using setInterval while the mouse is down and moving, I receive an error message stating 'Uncaught TypeError: Cannot re ...

Use npm to include a new dependency from the current dependency structure

I am currently working on a Vue application that utilizes both vuetable-2 and vue-axios. In my app.js file, I have the following imports: import Vue from 'vue' import VueMaterial from 'vue-material' import axios from 'axios' ...

Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout: src components Footer.vue views Page.vue App.vue I want to access the 'message' vari ...

Employ a string in order to execute a JSON command

Here's the scenario: var test = "toAdd"; I am trying to extract data from a JSON using this string: console.log(value.stats.test); The issue here is that test is being treated as a literal string and not as a variable. How can I get it to be recog ...

What could be causing the issue with the theme not functioning properly in Material-UI?

I'm currently working on implementing a unique theme-switching feature in my web application, allowing users to toggle between light and dark modes. Utilizing the Material-UI framework combined with React, here's the code snippet: const theme = c ...

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...

How can we address the tagging directive problem of binding tags as an array of JSON objects and ensuring that tagging functions properly with the ng-keypress event?

Check out this plnkr example. I'm having trouble binding my tags list with ng-model. I want to bind the tags as an array of objects on a function call using ng-keypress, and then post it to a json file in a specific format. Here is what I am looking f ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

The DOM fails to reflect changes in the data variable in VueJS

I am facing an issue while trying to update an array of arrays and display it as a reactive variable, however the DOM does not seem to reflect those changes. To achieve this, I have two components - a parent component and a child component: Parent Compon ...