我有这段代码从 WebAPI 方法中检索 json 数据,然后将其放入字符串中:
const 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))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var nowIveGotUYouDirtyRat = fastJSON.JSON.Instance.ToObject(s);
. . . // now what?
...但是我现在如何使用该对象化字符串来解析 json 数组的元素(它应该分配给“nowIveGotUYouDirtyRat”)?
该文档似乎将极简主义发挥到了极致,至少就如何实现这一点而言(http://www.codeproject.com/Articles/159450/fastJSON#usingcode)。
此外,虽然我下载并编译了 fastJSON net35.csproj,但生成的 .dll (fastJSON) 说它的版本是 2.0.0.0 - 不应该是 3.5.0.0 吗?(运行时版本 == v2.0.50727)
更新
Alrik,我的解决方案是切换到 JSON.NET。以下是您可以这样做的方法:
try
{
const string uri = "http://localhost:28642/api/departments/1/42";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
// GET is the default method/verb, but it's here for clarity
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
MessageBox.Show(string.Format("Content from HttpWebRequest is {0}", s));
var arr = JsonConvert.DeserializeObject<JArray>(s);
int i = 1;
foreach (JObject obj in arr)
{
var id = (string)obj["Id"];
var accountId = (double)obj["AccountId"];
var departmentName = (string)obj["DeptName"];
//MessageBox.Show(string.Format("Object {0} in JSON array: id == {1}, accountId == {2}, deptName == {3}", i, id, accountId, departmentName));
i++;
}
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
或者,如果您只是追求一个值:
private void buttonGetDeptCount2_Click(object sender, EventArgs e)
{
MessageBox.Show(GetScalarVal("http://localhost:28642/api/departments/Count"));
}
private string GetScalarVal(string uri)
{
var client = new WebClient();
return client.DownloadString(uri);
}
注意:感谢 Jon Skeet 的惊人简单的WebClient.DownloadString()技巧。