使用Newtonsoft将Json反序列化为C#

时间:2016-06-13 20:34:14

标签: c# asp.net json.net

我需要解析以下JSON:

{
    "code": 200, 
    "status": "OK", 
    "response": {
        "course_accessJSON": null, 
        "in_progress": 1, 
        "completed": 0, 
        "passed": 0, 
        "location": "http://*************************************", 
        "subscription": {
            "started": 1465834293, 
            "expired": 1473869493, 
            "payment": "account"
        }, 
        "is_expired": false, 
        "course_progress": {
            "CMP1044": {
                "course_name_en": "Java Programming", 
                "no_of_lessons": 30, 
                "viewed": 1, 
                "viewed_start": 1465834789, 
                "viewed_end": null, 
                "cert_attemptsCSV": null, 
                "cert_resetsCSV": null, 
                "cert_serial": null, 
                "high_score": null, 
                "location": "http://***************************"
            }
        }
    }
}

我设法使用以下内容获取除course_progress项目中的值以外的所有元素:

SampleResourse obj = JsonConvert.DeserializeObject<SampleResourse>(s);            
Response.Write(obj.Response.CourseProgress.CMP1044.CourseNameEn.ToString());


class SampleResourse
{
  [JsonProperty("code")]
  public int respcode { get; set; }

  [JsonProperty("status")]
  public string respStatus { get; set; }

  [JsonProperty("response")]
  public Response2 Response { get; set; }
}

class Response2
{
  [JsonProperty("in_progress")]
  public int InProgress { get; set; }

  [JsonProperty("completed")]
  public int Completed { get; set; }

  [JsonProperty("passed")]
  public int Passed { get; set; }

  [JsonProperty("course_progress")]
  public CourseProgress CourseProgress { get; set; }

}

class CourseProgress
{

  [JsonProperty("CMP1044")]
  public CMP10442 CMP1044 { get; set; }
}

class CMP10442
{
  [JsonProperty("course_name_en")]
  public string CourseNameEn { get; set; }
}

我需要查看元素course_name_en,no_of_lessons,但是会有多个类似于"CMP1044"的属性。每个&#34; CMP&#34;物业将有一个唯一的号码。我想列出每个方面的进展情况。

1 个答案:

答案 0 :(得分:3)

只需更改以下内容:

3

要列出课程名称和ID,您可以这样做:

class Response2
{
    [JsonProperty("in_progress")]
    public int InProgress { get; set; }

    [JsonProperty("completed")]
    public int Completed { get; set; }

    [JsonProperty("passed")]
    public int Passed { get; set; }

    [JsonProperty("course_progress")]
    public Dictionary<string, CourseProgress> CourseProgress { get; set; }
}
class CourseProgress
{
    [JsonProperty("course_name_en")]
    public string CourseNameEn { get; set; }
}