如何将流转换回json?

时间:2013-10-15 17:01:04

标签: json .net-3.5 httpwebrequest streamreader httpwebresponse

在.NET 3.5 Compact Framework / Windows CE应用程序中,我需要使用一些返回json的WebAPI方法。 RestSharp看起来很不错,除了它不是CF-ready(详见Is Uri available in some other assembly than System in .NET 3.5, or how can I resolve Uri in this RestSharp code otherwise?)。

所以,我可能会使用HttpWebRequest。我可以使用以下代码从WebAPI方法返回值:

string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
    StreamReader reader = new StreamReader(webResponse.GetResponseStream());
    MessageBox.Show("Content is " + reader.ReadToEnd());
}
else
{
    MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}

...但是为了使用从reader.ReadToEnd()返回的内容:

enter image description here

...我需要将它转换回json,以便我可以使用JSON.NET(http://json.codeplex.com/)或SimpleJson(http://simplejson.codeplex.com/

这是否真实可行(将StreamReader数据转换为JSON)?如果是这样,怎么样?

更新

我正在尝试使用以下代码反序列化“json”(或看起来像json的字符串):

string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
    StreamReader reader = new StreamReader(webResponse.GetResponseStream());
    DataContractJsonSerializer jasonCereal = new DataContractJsonSerializer(typeof(Department));
    var dept = (Department)jasonCereal.ReadObject(reader.ReadToEnd());
    MessageBox.Show(string.Format("accountId is {0}, deptName is {1}", dept.AccountId, dept.DeptName));
}

...但是在“var dept =”行上得到两个错误信息:

0) The best overloaded method match for 'System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.IO.Stream)' has some invalid arguments

1) Argument '1': cannot convert from 'string' to 'System.IO.Stream'

因此,reader.ReadToEnd()返回一个字符串,而DataContractJsonSerializer.ReadObject()显然需要一个流。有更好的方法吗?或者,如果我在正确的轨道上(虽然目前已经删除了一部分音轨,可以这么说),我该如何克服这个障碍呢?

更新2

我添加了System.Web.Extensions引用,然后“使用System.Web.Script.Serialization;”但是这段代码:

JavaScriptSerializer jss = new JavaScriptSerializer();
var dept = jss.Deserialize<Department>(s);
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}",  
    dept.AccountId, dept.DeptName));

...但第二行失败了:

类型'bla + Department'不支持反序列化数组。

什么类型应该接收对jss.Deserialize()的调用?它是如何定义的?

1 个答案:

答案 0 :(得分:1)

那么,

ReadToEnd()方法用于将流读入字符串并输出。如果需要流出来将其传递给需要流的方法,则不应使用此方法。 从我在this page上看到的内容来看,您的读者的BaseStream属性似乎更适合使用。