[英]Read online json data in windows phone 8.1
我正在开发Windows Phone 8.1的中心枢纽应用程序。 我正在访问Datamodel文件夹中的sampledata.json。 但是如何在线使用相同的sampledata.json文件。
该文件可通过使用来访问
Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");
和数据正在通过使用解析
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
string jsonText = await FileIO.ReadTextAsync(file);
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonArray = jsonObject["Groups"].GetArray();
foreach (JsonValue groupValue in jsonArray)
{
JsonObject groupObject = groupValue.GetObject();
SampleDataGroup group = new SampleDataGroup(groupObject["UniqueId"].GetString(),
groupObject["Title"].GetString(),
groupObject["Subtitle"].GetString(),
groupObject["ImagePath"].GetString(),
groupObject["Description"].GetString());
foreach (JsonValue itemValue in groupObject["Items"].GetArray())
{
JsonObject itemObject = itemValue.GetObject();
group.Items.Add(new SampleDataItem(itemObject["UniqueId"].GetString(),
itemObject["Title"].GetString(),
itemObject["Subtitle"].GetString(),
itemObject["ImagePath"].GetString(),
itemObject["Description"].GetString(),
itemObject["Content"].GetString()));
}
this.Groups.Add(group);
}
我想做httprequest,我也尝试过
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(new Uri("http://url/sampledata.json"));
string jsonString = await response.Content.ReadAsStringAsync();
在这之后我很震惊。 请帮忙
我有一些帮助方法,可以将JSON自动转换为所需的类型。 我的ASP.NET WebAPI服务返回JSON,我也以JSON格式发布数据。
public static async Task<TRes> Post<TReq, TRes>(string url, TReq data, HttpClient httpClient)
{
HttpContent content = ToJsonHttpContent(data);
HttpResponseMessage response = await httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.Extract<TRes>();
}
public static async Task<T> Extract<T>(this HttpContent me)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (Stream stream = await me.ReadAsStreamAsync())
{
return (T)serializer.ReadObject(stream);
}
}
public static HttpContent ToJsonHttpContent(object data)
{
string jsonData = JsonConvert.SerializeObject(data);
return new StringContent(jsonData, Encoding.UTF8, "application/json");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.