2015-11-22 97 views
-1

解析來自URL的JSON數組。但班級名稱中有「 - 」,U怎麼辦?使用C#解析來自URL的JSON數組,使用 - in classname

例如:

{ 
    "my-class": [ 
    { 
     "class_name": "1H", 
     "class_room": "201aTD", 
     "day": "26", 
     "month": "10", 
     "period": "2", 
     "subject": "IF", 
     "teacher": "J04", 
     "year": "2015" 
    }] 
} 

編輯:

這是我的代碼我嘗試。但我沒有得到名單。

public void gettimetable(string s) { 
      string get = getTimeTable(s); 

      JObject o = JObject.Parse(get); 

      var obj = JsonConvert.DeserializeObject<RootObject>(get); 


      TextBox1.Text = (obj.MyClass.ToString()); 

      // TextBox1.Text=(obj.class_room[0].ToString()); 
     } 

回答

0

您可以輕鬆地通過使用JsonProperty屬性標註你的類實現這一目標與Json.NET

static void Main(string[] args) 
{ 
    var json = "{\"my-class\": [{\"class_name\": \"1H\", 
           \"class_room\": \"201aTD\", 
           \"day\": \"26\", 
           \"month\": \"10\", 
           \"period\": \"2\", 
           \"subject\": \"IF\", 
           \"teacher\": \"J04\", 
           \"year\": \"2015\"}]}"; 

    Console.WriteLine(JsonConvert.DeserializeObject<RootObject>(json)); 
} 

public class RootObject 
{ 
    [JsonProperty("my-class")] 
    public List<MyClass> MyClass { get; set; } 
} 

public class MyClass 
{ 
    [JsonProperty("class_name")] 
    public string ClassName { get; set; } 
    [JsonProperty("class_room")] 
    public string ClassRoom { get; set; } 
    [JsonProperty("day")] 
    public string Day { get; set; } 
    [JsonProperty("month")] 
    public string Month { get; set; } 
    [JsonProperty("period")] 
    public string Period { get; set; } 
    [JsonProperty("subject")] 
    public string Subject { get; set; } 
    [JsonProperty("teacher")] 
    public string Teacher { get; set; } 
    [JsonProperty("year")] 
    public string Year { get; set; } 
}