gpt4 book ai didi

c# - 将 JSON 对象写入 Windows Phone 隔离存储

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:52 26 4
gpt4 key购买 nike

我正在尝试将从 Azure 移动服务 返回的 JSON 对象保存到 Windows Phone 独立存储。我从下面的代码开始,但我不完全确定如何将文件实际写入独立存储或将其保存为何种格式(XML、TXT 等)。

        string offlineData = Path.Combine("WPTracker", "Offline");
string offlineDataFile = Path.Combine(offlineData, "phones.xml");
var store = IsolatedStorageFile.GetUserStoreForApplication();

//Query
try
{
phoneList = await phoneTable
.Where(PhoneItem => PhoneItem.Publish == true)
.OrderBy(PhoneItem => PhoneItem.FullName)
.ToListAsync();
}
catch (MobileServiceInvalidOperationException f)
{
MessageBox.Show(f.Response.Content.ToString(),
string.Format("{0} (HTTP {1})",
f.Response.Content,
f.Response.StatusCode), MessageBoxButton.OK);
}

//Write
IsolatedStorageFileStream dataFile = null;
dataFile = store.OpenFile(offlineDataFile, FileMode.Create);
DataContractSerializer ser = new DataContractSerializer(typeof(IEnumerable<Phones>));

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jWriter = new JsonTextWriter(sw);

ser.WriteObject(dataFile, phoneList);
dataFile.Close();

有什么建议吗? :)

编辑

我决定使用 JSON 文件而不是 XML 将数据写入独立存储。这是因为我来自 Azure 移动服务的数据是以 JSON 格式发送的。无需将其转换为 XML。可以在下面找到链接!

最佳答案

下面是如何保存 json 以及如何检索它的示例。

public partial class MainPage : PhoneApplicationPage
{
const string MyDirectory = "offline";
readonly string _offlineDataFile = Path.Combine(MyDirectory, "phones.json");
public MainPage()
{
InitializeComponent();

Loaded += MainPage_Loaded;
}

async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var httpClient = new HttpClient();
var data = await httpClient.GetStringAsync("http://www.tapanila.net/api/get_recent_posts/");
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.DirectoryExists(MyDirectory))
{
store.CreateDirectory(MyDirectory);
}


using (var fileStream = new IsolatedStorageFileStream(_offlineDataFile, FileMode.Create, store))
{
using (var stream = new StreamWriter(fileStream))
{
stream.Write(data);
}
}
LoadOffline();
}

private void LoadOffline()
{
var store = IsolatedStorageFile.GetUserStoreForApplication();

using (var fileStream = new IsolatedStorageFileStream(_offlineDataFile, FileMode.Open, store))
{
using (var stream = new StreamReader(fileStream))
{
var data = stream.ReadToEnd();
}
}
}
}

关于c# - 将 JSON 对象写入 Windows Phone 隔离存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18425822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com