嗨,我有一个json响应,例如
{"状态":"成功","消息":"身份验证 成功","数据":{" key":" sdsdirs9iebe6qhmawlbscks9mqfut6jkynq%2bw"," userId":" ddjjj8-11e6-637af7}}}
我如何解析此响应。
我正在这样做:
private void POST(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
postData="{"UserName": "abc"," +""Password": "mypwd"}";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = @"application/x-www-form-urlencoded";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
using (var reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
string str= objText;
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
我能够读取"状态"one_answers"消息",但无法读取"键"one_answers"用户ID"值。
请帮助!
您可以使用Newtonsoft Json
而不是JavaScriptSerializer
JSON的类结构看起来像
public class Rootobject
{
public string Status { get; set; }
public string Message { get; set; }
public Data Data { get; set; }
}
public class Data
{
public string Key { get; set; }
public string UserId { get; set; }
}
可以像
那样轻松地进行挑战Rootobject ro = JsonConvert.DeserializeObject<Rootobject>(json);
Console.WriteLine(ro.Status + ", " + ro.Message + ", " + ro.Data.Key + ", " + ro.Data.UserId);
猜测(因为我们不知道MyObject类的结构)如何访问数据:
String status = myobj.status;
String message = myobj.message;
现在,由于其他数据属性在JSON的"数据"节点中,因此您应该能够这样访问它们:
String key = myobj.data.key;
String userId = myobj.data.userId;