将Json字符串转换为对象列表

6

我从一个外部的webapi获取了一个包含json对象的字符串。我有一段代码将这些对象转化为ExpandoObject列表,但是除了使用动态对象之外,还应该有其他解决方案。

以下是代码:

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": "mail@mail.com",
          "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)
1个回答

2

您可以使用众多的C# JSON解析器之一来完成这个任务。我个人更喜欢JSON.Net(您可以通过NuGet安装它)。它可以将JSON反序列化为动态对象,也可以反序列化为您自己静态类型的类。


1
如果可能的话,我不想使用外部库。 - Aleks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接