如何使用fastJSON使用反序列化数据?

时间:2013-10-15 22:11:40

标签: httpwebrequest asp.net-web-api httpwebresponse json-deserialization fastjson

我有这个代码从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?

...但是我现在如何使用该objectized字符串来解析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()小费。

0 个答案:

没有答案