Home > Software engineering >  C# http-get url JSON data and parse it to text..?
C# http-get url JSON data and parse it to text..?

Time:10-27

I don't really know how to ask this but basically,

I have a url http://URL.com/filename.json and I would like to fetch the data from /filename.json and "convert it to text". The url file contains the following: {"CurrentVersion": "1.0"} and I would like to get the CurrentVersion and define a string with its value (1.0).

using Newtonsoft.Json
//Here is what I tried

string url = "http://url";

using (webClient)
{
  var jsonstring = webClient.DownloadString(url);
  string versionid1 = JsonConvert.DeserializeObject < CurrentVersion > jsonstring; //I am comfused here.. It won't let me continue because CurrentVersion is not defined or something.
  currentver = versionid1;
  Console.Write(versionid1); // To ensure
}

CodePudding user response:

One possibility is to make use of System.Net.WebClient for downloading the data:

string json;
using(var webClient = new WebClient())
{
   json = webClient.DownloadString("http://URL.com/filename.json");
}

after downloading the string you can deserialize it with a framework like Json.Net. Because it is a simple JSON file we can deserialize it into a dictionary. This way we do not have to create an explicit class for it:

var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Now we can access the version like this:

var versionString = dict["CurrentVersion"];
  • Related