我是C#的新手,我正在尝试联系服务器并从服务器接收数据。我可以成功接收数据,但我不知道如何访问对象的属性。我想要的只是显示 SessionID ,例如的" biRvqpChQZf7Cujy5CuW0PjU1R7gIp"
WebRequest LoginRequest = WebRequest.Create("xxx");
LoginRequest.Method = "GET";
WebResponse LoginResponse = LoginRequest.GetResponse();
Stream LoginResponseStream = LoginResponse.GetResponseStream();
StreamReader reader = new StreamReader(LoginResponseStream);
string responseFromServer = reader.ReadToEnd();
string TheText = new JavaScriptSerializer().Serialize(responseFromServer);
Label1.Text = TheText;
现在TheText的结果是:
" {\" utLogon_response \":{\" SessionID的\":\" rP99mnHAFwI840xVJMDOJpcgmE2l6z \"}}& #34;
这是对象"手动"来自HTML:
答案 0 :(得分:2)
您需要反序列化
在此示例中,RootObject应该是您的类:
*如果你没有get; class;您可以在this网站http://json2csharp.com/
创建该属性只需将您的json字符串粘贴到该网站(json2csharp),即可获得所有财产。
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);
一步一步
假设您的json是:
string TheText = "{\"utLogon_response\":{\"SessionID\":\"rP99mnHAFwI840xVJMDOJpcgmE2l6z\"}}";
这些是基于你的json的课程:
public class UtLogonResponse
{
public string SessionID { get; set; }
}
public class RootObject
{
public UtLogonResponse utLogon_response { get; set; }
}
然后使用此代码:
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(TheText);
var yourSessionId = oRootObject.utLogon_response.SessionID; //Done !
答案 1 :(得分:2)
您需要创建一个对象,然后反序列化而不是序列化它。您可以使用JSON.net对其进行反序列化。
class Test
{
public string SessionID { get; set; }
}
//after getting response from server
Test tmp = JsonConvert.DeserializeObject<Test>(responseFromServer);
Label1.Text = tmp.SessionID;
以下链接可能会对您有所帮助:
https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
答案 2 :(得分:0)
您是否尝试使用字符串SessionId属性创建utLogon_response并执行以下操作: var text = Jsonconvert.DeserializeObject(responseFromServer)