我正在从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:值不能为null。
当我遍历列表时
foreach (var item in resultsList)
{
<a>@item.media</a>
}
每个媒体项目都是 System.Web.Helpers.DynamicJsonArray 。
我需要阅读这个数组,所以我可以得到每个图像的网址和大小。
以上json网址是公开的。 我在Umbraco 7中使用剃刀代码(aps mvc 4)。
答案 0 :(得分: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);