1

我正在阅读来自https://demoapi.thismoment.com/v4.1/api/content的 Json

将其作为流读取:

Stream stream = wc.OpenRead(url);
using (StreamReader reader = new StreamReader(stream))
{
String request = reader.ReadToEnd();
var requestJson = @Json.Decode(request);

并获取结果列表

var resultsList = new List<dynamic>(requestJson.results);

尝试阅读下一个级别时

var resultsList = new List<dynamic>(requestJson.results.media);

我收到此错误: System.ArgumentNullException:值不能为空。

当我遍历列表时

foreach (var item in resultsList)
{
<a>@item.media</a>
}

每个媒体项都是System.Web.Helpers.DynamicJsonArray

我需要读取这个数组,所以我可以获得每个图像的 url 和大小。

上面的 json url 是公开的。我正在使用剃须刀代码(aps mvc 4)的 Umbraco 7 中执行此操作。

4

1 回答 1

1

您可以使用以下方法来做到这一点:

private static List<T> GetcollectionFromJason<T>(string jasonUrl) where T : new()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(jasonUrl);
            List<T> retCollection = new List<T>();
            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        string jsonString = reader.ReadToEnd();
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        retCollection = serializer.Deserialize<List<T>>(jsonString);

                    }
                }
            }
            catch (WebException exp)
            {
                WebResponse errorResponse = exp.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                        String errorText = reader.ReadToEnd();
                    }
                }
            }

            return retCollection;
        }

并称它为你可以有这个:

List<YourModel> technicalIssues = GetcollectionFromJason<YourModel>(YourJsonUrl);
于 2014-05-21T10:46:39.943 回答