2013-04-03 94 views
5

我從外部webapi獲取帶有json對象的字符串。我有一個代碼將對象獲取到ExpandoObject列表中,但必須有另一個解決方案,而不使用動態對象。將Json字符串轉換爲對象列表

下面是代碼:

System.Net.HttpWebRequest request = 

(System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://example.com/api/users.json"); 
request.Credentials = System.Net.CredentialCache.DefaultCredentials; 
request.Headers["Authorization"] = "API key="+somekey; 
// Ignore Certificate validation failures (aka untrusted certificate + certificate chains) 
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); 

System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); 
Stream resStream = response.GetResponseStream(); 
StreamReader reader = new StreamReader(resStream); 
//response from the api 
string responseFromServer = reader.ReadToEnd(); 
//serialize the data 
var jss = new System.Web.Script.Serialization.JavaScriptSerializer(); 
System.Collections.IList users = (System.Collections.IList)((IDictionary<string, object>)((IDictionary<string, object>)jss.DeserializeObject(responseFromServer))["data"])["users"]; 

List<System.Dynamic.ExpandoObject> api_users = new List<System.Dynamic.ExpandoObject>(); 
//putting the expandable objects in list 
foreach (var u in users) 
{ 
    var user = ((Dictionary<string, object>)((IDictionary<string, object>)u)["User"]); 
    dynamic data = new System.Dynamic.ExpandoObject(); 
    //putting the user attributes into dynamic object 
    foreach (var prop in user) 
    { 
     ((IDictionary<String, Object>)data).Add(prop.Key, prop.Value); 
    } 
    api_users.Add(data); 
} 

這裏是JSON字符串的示例:

"data": { 
    "users": [ 
     { 
     "User": { 
      "user_id": "6741", 
      "email": "[email protected]", 
      "first_name": "Mark", 
      "last_name": "Plas", 
      "street_address": "", 
      "post_code": "", 
      "city": "" 
     }, 
     "CreatedBy": { 
      "id": null, 
      "name": null 
     }, 
     "ModifiedBy": { 
      "id": null, 
      "name": null 
     } 
     },...(can have more users here) 

回答

2

可以使用許多C#JSON解析器之一來做到這一點。我個人更喜歡JSON.Net(你可以通過NuGet安裝)。它可以反序列化爲動態對象以及您自己的靜態類型的類。

+0

我不想使用外部庫,如果可能的話 – Aleks 2013-04-04 08:09:29

相關問題