将JSON数据添加到泛型集合

时间:2015-09-28 14:13:26

标签: c# .net json c#-4.0

至少在谈到这样的事情时,我对C#还是比较新的,所以我为我的少量代码道歉。

我有一个名为Project.cs的类,需要用它来保存我从第三方API获得的数据对象。

这是班级:

// Project.cs

public sealed class Project
{
    public String Id { get; set; }
    public String Title { get; set; }
    public String Url { get; set; }
}

您在下面看到的方法应该从第三方API获取数据(JSON)。

此API以JSON格式返回项目列表。

幸运的是,我只需要从API(Id,Title和URL)中选择一些属性。

不幸的是,我不知道如何从JSON中选择那些特定属性并将它们转换为Project类型的集合。

这是我到目前为止所拥有的。我知道它很稀疏。

// ProjectSearch.cs

public IEnumerable<Project> GetProjects(String catId)
{
    //Get the data from the API
    WebRequest request = WebRequest.Create("http://research.a.edu/api/Catalogs('123')");
    request.ContentType = "application/json; charset=utf-8";
    WebResponse response = request.GetResponse();

    //put each object found in the API into a Project object        
    var project = new Project();

}

所以,现在,我被卡住了。我不知道如何从API获取所有对象并将它们放入Project类型的集合中。我需要循环吗?或者还有其他类型的做法吗?

API中的示例JSON:

{"odata.metadata":"http://research.a.edu/api/Catalogs/
$metadata#Catalogs /@Element", "odata.id":"http://research.a.edu/api/Catalogs
('123')",
"Id":"12345", "ParentID":"xxxx","Name":"Test1","Created":"1/1/2015","Modified":"2/1/2015","Deleted","0","URL":"http://yoursite/1",
('123')",
"Id":"7897", "ParentID":"xxxx","Name":"Test2","Created":"4/1/2015","Modified":"7/1/2015","Deleted","1","URL":"http://yoursite/2",
('123')",
"Id":"65335", "ParentID":"xxxx","Name":"Test3","Created":"7/1/2015","Modified":"9/1/2015","Deleted","0","URL":"http://yoursite/3"
}

我输了。

如果有人能提醒我,我会感激不尽。

谢谢!

2 个答案:

答案 0 :(得分:3)

您应该查看最受欢迎的.NET JSON库:Newtonsoft JSON

用法非常简单。此示例取自网站:

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;

答案 1 :(得分:1)

我有两个实用功能,我只为此目的而保留(一个用于GET,另一个用于POST)。它使用泛型作为返回类型,因此可以“随处”使用。

    public static T RetrieveContent<T>(string url)
    {
        if (String.IsNullOrWhiteSpace(url))
            throw new ArgumentNullException("url");

        T returnValue = default(T);

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "application/json; charset=utf-8";
            using (WebResponse response = request.GetResponse())
            {
                if (response != null)
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        var serializer = new JsonSerializer();
                        var jsonTextReader = new JsonTextReader(reader);
                        returnValue = serializer.Deserialize<T>(jsonTextReader);
                    }
                }
            }
        }
        catch (Exception e)
        {
            string errMsg = String.Format("UtilitiesBL:RetrieveContent<T>(url). There was an error retrieving content from URL: {0}.", url);
            throw new Exception(errMsg, e);
        }

        return returnValue;

    }

    public static T RetrieveContentPost<T>(string url, string postData)
    {
        if (String.IsNullOrWhiteSpace(url))
            throw new ArgumentNullException("url");

        T returnValue = default(T);


        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            byte[] contentBytes = Encoding.UTF8.GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = contentBytes.Length;
            request.Accept = "application/json; charset=utf-8";

            // Get the request stream.
            using(Stream dataStream = request.GetRequestStream())
            {
                // Write the data to the request stream.
                dataStream.Write(contentBytes, 0, contentBytes.Length);
            }
            using (WebResponse response = request.GetResponse())
            {
                if (response != null)
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        var serializer = new JsonSerializer();
                        var jsonTextReader = new JsonTextReader(reader);
                        returnValue = serializer.Deserialize<T>(jsonTextReader);
                    }

                }
            }
        }
        catch (Exception e)
        {
            string errMsg = String.Format("UtilitiesBL:RetrieveContentPost(url, postData). There was an error retrieving content from URL: {0}.", url);
            throw new Exception(errMsg, e);
        }

        return returnValue;

    }

使用问题中的示例,您的代码将如下所示:

public IEnumerable<Project> GetProjects(String catId)
{
    string url = String.Format("http://research.a.edu/api/Catalogs('{0}')", catId);
    return RetrieveContent<List<Project>>(url);
}