将JSON对象写入Windows Phone独立存储

时间:2013-08-25 04:54:07

标签: c# json windows-phone-8 json.net azure-mobile-services

我正在尝试将从JSON返回的Azure Mobile Services对象保存到Windows Phone isolated storage。我已经开始使用下面的代码,但我不完全确定如何将文件实际写入隔离存储或将其保存在哪种格式(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 Mobile Services获取的数据是以JSON格式发送的。无需将其转换为XML。链接可以在下面找到!

2 个答案:

答案 0 :(得分:1)

以下是如何保存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();
            }
        }
    }
}

答案 1 :(得分:1)

可以找到有关如何将JSON对象写入Windows Phone中的独立存储的指南here