无法解析JSON流,

时间:2015-01-24 01:47:17

标签: c# asp.net json

我可以使用C#.Net中的基本身份验证和HTTPWebResponse连接到供应商的Web API。我能够在StreamReader中获取JSON流,但在解析JSON时,我得到的是null值,无法在单个字符串或变量中获取数据元素。请参阅随附的JSON文件并提供帮助......

这是我的代码......

 username = "****";
 var password = "***";
 var url = "*****";
 var encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username  + ":" + password));
 var webRequest = (HttpWebRequest)WebRequest.Create(url);
 webRequest.Headers.Add("Authorization", "Basic " + encoded);
 webRequest.Method = "GET";
 webRequest.Accept = "application/json";
 webRequest.ContentType = "application/json";


 var webResponse = (HttpWebResponse)webRequest.GetResponse();
 var reader = new StreamReader(webResponse.GetResponseStream());
 string s = reader.ReadToEnd();

尝试了解决方案,但遇到了麻烦。下面是我的一些JSON流。

  

{" status":" success"," message":"已成功处理笔记请求。已经返回了100条记录。","数据":[{" noteId":" 0000"," studentId":& #34; 000000"" advisorId":" 0000111"" dateCreated会":&#34 01 /二千零十五​​分之二十零"&# 34; studentStatus":" On path"," noteBody":"这是一个测试笔记,适用于特定学生。它适用于学生000000",#34;编辑":" N"," dateEdited":" N / A",&#34 ; privateNote":" N""除去":" N"" removedDate":" N / A&# 34;," displayDate":&#34 01 /二千零十五​​分之二十零"" noteCreatedWithReminder":" N"" noteCreatedWithStatusChange&#34 ;:" N"},{" noteId":" 0001"" studentId":" 000001",& #34; advisorId":" 0000111"" dateCreated会":&#34 01 /二千零十五​​分之二十○"" studentStatus":&# 34;正在进行"," noteBody":"这是一个测试笔记,它适用于特定的学生。它适用于学生000001","编辑":" N"," dateEdited":" N / A",&#34 ; privateNote":" N""除去":" N"" removedDate":" N / A&# 34;," displayDate":&#34 01 /二千零十五​​分之二十零"" noteCreatedWithReminder":" N"" noteCreatedWithStatusChange&#34 ;:" Y"}

1 个答案:

答案 0 :(得分:2)

我建议使用JSON.net这样的库,这样可以更容易解析,你需要做的就是创建模型类:

public class Note
{
    public string noteId { get; set; }
    public string studentId { get; set; }
    public string advisorId { get; set; }
    public string dateCreated { get; set; }
    public string studentStatus { get; set; }
    public string noteBody { get; set; }
    public string edited { get; set; }
    public string dateEdited { get; set; }
    public string privateNote { get; set; }
    public string removed { get; set; }
    public string removedDate { get; set; }
    public string displayDate { get; set; }
    public string noteCreatedWithReminder { get; set; }
    public string noteCreatedWithStatusChange { get; set; }
}

public class Response
{
    public string status { get; set; }
    public string message { get; set; }
    public List<Note> notes { get; set; }
}

那么这就是你解析它的方式

var response = JsonConvert.DeserializeObject<Response>(json);
Console.WriteLine("status =" + response.status);