【发布时间】:2013-10-23 14:11:15
【问题描述】:
在 .NET 3.5 Compact Framework / Windows CE 应用程序中,我需要使用一些返回 json 的 WebAPI 方法。 RestSharp 看起来很适合这个,只是它还没有完全支持 CF(请参阅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() 返回的内容:
...我需要将其转换回 json,然后我可以使用 JSON.NET (http://json.codeplex.com/) 或 SimpleJson (http://simplejson.codeplex.com/) 使用 LINQ to JSON 查询数据
这真的可能吗(将 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() 的调用?它是如何定义的?
【问题讨论】:
-
从我看到的地方,不是 JSON 吗? (当然除了“内容是”的介绍......我想你是出于调试原因添加的)
-
它看起来像 JSON,但这是 StreamReader.ReadToEnd() 返回的吗?我对此表示怀疑。它可能只是字节数组的字符串表示或类似的东西。 IOW,JSON 反序列化器是否能够对其进行正面或反面?
-
如果我没记错的话,ReadToEnd() 返回一个字符串,在这种情况下,它似乎正确格式化为 JSON,我很确定你可以用它来提供反序列化器......最好的将是测试,因为我认为我们正在讨论一个非问题......
-
我更新了我的帖子,详细介绍了尝试反序列化。
标签: json .net-3.5 httpwebrequest streamreader httpwebresponse