我正在为Windows Phone 8.1开发一个hub-pivot应用程序。我正在访问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();
在此之后,我很震惊。请帮忙
答案 0 :(得分:0)
我有一些帮助方法可以将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");
}