如何解析包含C#list

时间:2016-12-19 09:22:18

标签: c# json rest asp.net-web-api json.net

嗨,我有一个json响应,如

  

{ “状态”: “成功”, “消息”:“认证   成功”, “数据”:{ “关键”: “sdsdIRs99Iebe6QHmawlBsCks9mqfUt6jKYNQ%2BW”, “用户ID”: “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
    }
}

我能够阅读“状态”和“消息”但无法读取“密钥”和“用户ID”值。

请帮忙!

2 个答案:

答案 0 :(得分:5)

您可以使用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);

答案 1 :(得分:1)

猜测(因为我们不知道MyObject类的结构)如何访问数据:

String status = myobj.status;
String message = myobj.message; 

现在,由于其他数据属性位于json的“data”节点中,因此您应该可以像这样访问它们:

String key = myobj.data.key;
String userId = myobj.data.userId;