如何反序列化JSON

时间:2014-02-03 14:05:57

标签: c# asp.net json deserialization webclient

我正在开展项目,其中我将数据从asp.net webform发布到WCF服务。我通过params发布数据,服务回复JSON string。现在我在反序列化方面遇到了问题。我读了很多线程,但没有找到任何解决方案。希望有人能解决我的问题。在此先感谢

来自WCF的回复

{ “LoginResult”:假}

我只想要"false"值。

我是怎么做的:

    string URL = "http://localhost:32319/ServiceEmployeeLogin.svc"; 
    WebRequest wrGETURL;
    wrGETURL = WebRequest.Create(URL+"/"+emp_username+"/"+emp_password+"/"+emp_type);
    wrGETURL.Method = "POST";
    wrGETURL.ContentType = @"application/json; charset=utf-8";
    HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;

    Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
    // read response stream from response object
    StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);

    // read string from stream data
    strResult = loResponseStream.ReadToEnd();

    var jObj = JObject.Parse(strResult);
    var dict = jObj["LoginResult"].Children().Cast<JProperty>();

2 个答案:

答案 0 :(得分:6)

您可以使用json.net这样做:

public class AuthResponse {
    public bool LoginResult { get; set; }
}

var deserializedResponse = JsonConvert.DeserializeObject<AuthResponse>(strResult);

http://james.newtonking.com/json

答案 1 :(得分:2)

.Net 4.5有一个JavaScriptSerializer,它也可以运行:

public class AuthResponse {
    public bool LoginResult { get; set; }
}

System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer();

AuthResponse response = sr.Deserialize<AuthResponse>(responseText);

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx