我正在使用 HttpWebRequest 和 HttpWebResponse 从 WebAPI 方法获取 JSON。但是我需要序列化/反序列化/解析该数据。
本机 JavaScriptSerializer 已被权衡并发现不足。我尝试了 fastJSON,但它的文档非常缺乏;我拒绝了 Simple.JSON,因为它是 Beta 版,我不确定它是否支持适用于 .NET 3.5 的 Compact Framework。我终于转向了来自 Isaacsoft 的可靠的旧 JSON.NET,但对于如何提取 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();
MessageBox.Show(s);
JsonArray depts = JsonConvert.DeserializeObject<JsonArray>(s);
MessageBox.Show(string.Format("count is {0}", depts.Count)); // this is right; it shows 6
. . .
如最后一条评论所示,我想要的数据正在进入部门,因为它显示的数字是正确的 - 当“s”为 messagebox.Shown() 时显示 6 个 JSON“记录”(数组成员?)。
但是如何从这里着手呢?这段被注释掉的代码将讲述我向其中投掷网的一些方向的悲惨故事,四处乱窜,但到目前为止失败了:
//List<Department> ld = JsonConvert.SerializeObject(depts).to;
//foreach (JObject jso in depts)
//{
// jso.Values()
//}
//object id, accountId, deptName;
//JToken id, accountId, deptName;
////foreach (JsonObject jso in depts)
////{
//// if (jso.TryGetValue("id", out id))
//// {
//// MessageBox.Show(id.ToString());
//// }
////}
//foreach (JObject jso in depts)
//{
// if (jso.TryGetValue("id", id))
// {
// MessageBox.Show(id.ToString());
// }
//}
//JsonObject dept = depts[0] as JsonObject;
//Department dept = depts[0] as Department;
//Department dept = depts[0].
//MessageBox.Show(string.Format("first record: id is {0}, accountId is {1}, deptName is {2}", dept.Id, dept.AccountId, dept.DeptName));
//int id = depts[0].
//string accountId = depts[0].AccountId;
//string deptName = depts[0].DeptName;
//MessageBox.Show(string.Format("accountId is {0}, deptName is {1}", accountId, deptName));
更新
为了响应 Brian Rogers 查看 json 的请求,这段代码:
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
MessageBox.Show(s);
...产生这个:
更新 2
这是测试 JSON:
[{"Id":0,"AccountId":"7.0","DeptName":"Dept7"},{"Id":1,"AccountId":"8.0","DeptName":"Dept8"},{ "Id":2,"AccountId":"9.0","DeptName":"Dept9"},{"Id":3,"AccountId":"10.0","DeptName":"Dept7"},{"Id ":4,"AccountId":"11.0","DeptName":"Dept7"},{"Id":5,"AccountId":"12.0","DeptName":"Dept8"}]