我的意思是,这是我的代码:
// 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:UsersadminDocumentsVisual Studio 2015ProjectsWriteText.json", myString);
}
// JSON deserialize from a file
String JSONstring = File.ReadAllText(@"C:UsersadminDocumentsVisual Studio 2015ProjectsWriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(JSONstring);
如果不保存流并再次将其加载到字符串,我怎么能做到这一点呢?我想使用我的流直接到字符串'JSONstring',然后解析它。
您的代码包含解决方案
// 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:UsersadminDocumentsVisual Studio 2015ProjectsWriteText.json", myString);
}
// JSON deserialize from a file
// String JSONstring = File.ReadAllText(@"C:UsersadminDocumentsVisual Studio 2015ProjectsWriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(reader.ReadToEnd());
reader.close();
下面是一个如何将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;
}
}
}