我尝试将JSON写入这样的文件:
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;
}
当我调试错误时......
System.InvalidCastException:指定的强制转换无效。
...在这一行:
File.WriteAllText(filename, json);
我的错误在哪里?
答案 0 :(得分:1)
从URL获取JsonString的片段
char *
要调用上述方法并将字符串保存到本地文件的代码段。
char[]
稍后从该文件中读取该JsonString并将其转换为Json
的片段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;
}