Reputation:
I try to write JSON to file like this:
string url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=83";
JsonValue json = await FetchAsync(url2);
var path = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ApplicationData);
var filename = Path.Combine(path, "cache.txt");
File.WriteAllText(filename, json);
public async Task<JsonValue> FetchAsync(string url)
{
System.IO.Stream jsonStream;
JsonValue jsonDoc;
using (var httpClient = new System.Net.Http.HttpClient())
{
jsonStream = await httpClient.GetStreamAsync(url);
jsonDoc = JsonObject.Load(jsonStream);
}
return jsonDoc;
}
When I debug I the an error ...
System.InvalidCastException: Specified cast is not valid.
... in this line:
File.WriteAllText(filename, json);
Where is my mistake?
Upvotes: 2
Views: 814
Reputation: 2434
Snippet to Get JsonString From the URL
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
Snippet to Invoke the above method and Save the String to Local File.
string url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=83";
var json = await FetchAsync(url2);
var path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(path, "cache.txt");
File.WriteAllText(filename,json);
Snippet to later read that JsonString from that file and convert it to Json
JsonValue readJson;
var jsonString =File.ReadAllText(filename);
readJson = JsonObject.Parse(jsonString);
Upvotes: 1