2011-09-12 154 views
-1

可能重複:
How do i parse json?如何從JSON獲取數據

請告訴我反序列化asp.net C#中的JSON數據的方式。 其實我有喜歡的兩個對象一個JSON數據:

{ 
    "errstr": "All downloded vedios ", 
    "errcode": 0, 
    "result": { 
     "videos": [ 
      { 
       "id": "22", 
       "name": "Ashley", 
       "price": "0.49", 
       "size": "3712310" 
      } 
     ], 
     "trailer": [ 
      { 
       "id": "1", 
       "trailer_name": "charl1", 
       "status": "1" 
      }, 
      { 
       "id": "2", 
       "trailer_name": "charl2", 
       "status": "1" 
      } 
     ] 
    } 
} 

這裏我有兩個對象的視頻和預告片。請告訴我在我的代碼中獲取這些數據的過程。

回答

1

您需要創建例如JSON文件嵌套成員 類

{ 
"GeminiURL":"https://gemini.com/Gemini" 
,"Language":"en" 
,"Log":{"Debug":true,"Info":true,"Warn":true,"FileName":"d:\\temp\\tfsgemini.log"} 
} 

被serializaed與C#類

public class Settings 
{ 
    public string GeminiURL; 
    private LogSettings _log; 
    public LogSettings Log 
    { 
     get { return _log = _log ?? new LogSettings(); } 
     set { _log = value; } 
    } 
    public string Language; 

    public Settings() 
    { 
     // defaule settings can be assigned here; 
    } 
} 
public class LogSettings 
{ 
    public bool Debug; 
    public bool Info = true; 
    public bool Warn = true; 
    public string FileName; 
} 

和反序列化反序列化代碼如下所示:

public static T Load(string fileName) 
{ 
    T t = new T(); 
     if (File.Exists(fileName)) 
      t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName)); 
     else 
      Save(t); 
    return t; 
}