我的意思是,这是我的代码:
// Create the web request (posts/1)
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts/1") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
{
string myString = reader.ReadToEnd();
System.IO.File.WriteAllText(@"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json", myString);
}
// JSON deserialize from a file
String JSONstring = File.ReadAllText(@"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(JSONstring);
如何在不保存流并再次将其加载到字符串的情况下执行此操作。我想直接将我的流用于String&#39; JSONstring&#39;然后解析它。
答案 0 :(得分:1)
这是一个如何将HTTP流解析为Json(没有错误处理)的示例。玩它并告诉我们您是否遇到任何具体问题。在这段代码中。 API_Json是带有反序列化类的类,我正在反序列化API_Json.RootObject:
public async Task<API_Json.RootObject> walMart_Lookup(string url)
{
lookupIsWorking = true;
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (HttpClient http = new HttpClient(handler))
{
http.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
http.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
url = String.Format(url);
using (var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
Console.WriteLine(response);
var serializer = new JsonSerializer();
using (StreamReader sr = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
var root = serializer.Deserialize<API_Json.RootObject>(jsonTextReader);
lookupIsWorking = false;
return root;
}
}
//var obj = (API_Json_Special_Feeds.RootObject)serializer.Deserialize(sr, typeof(API_Json_Special_Feeds.RootObject));
//return obj;
}
}
}
答案 1 :(得分:1)
您的代码包含解决方案
// Create the web request (posts/1)
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts/1") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
{
//string myString = reader.ReadToEnd();
//System.IO.File.WriteAllText(@"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json", myString);
}
// JSON deserialize from a file
// String JSONstring = File.ReadAllText(@"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(reader.ReadToEnd());
reader.close();