2011-09-12 126 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; 
}