【问题标题】:Writing to json file Xamarin Android写入 json 文件 Xamarin Android
【发布时间】:2018-05-30 16:39:16
【问题描述】:

我正在制作一个应用程序,我需要将数据(json 格式)存储在物理设备上的文件中。

我遇到的问题是,通过将文件放在资产文件夹中,它们变成只读的,这是成功的一半,我可以读取它们,但是我应该将文件放在哪里以使它们可写?

当我将它们移动到 specialFolder.Personal 时,我遇到了空引用异常,当我将它们移动到其他任何地方时,我遇到了 accessDenied 异常。

感谢任何帮助(我对 Xamarin 还是很陌生,但我在 C# 方面确实有很好的经验)。

提前致谢。

    /// <summary>
    /// Method to read all data from player data json file.
    /// </summary>
    /// <returns></returns>
    public List<Player> GetAllPlayerData()
    {
        return ReadFile(playerdata);
    }

    ^^ This method is returning null.

    /// <summary>
    /// Method to read JSON data from a specified file path.
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    private List<Player> ReadFile(string path)
    {
        if (!(File.Exists(path)))
        {
            File.Create(path).Dispose();
        }

        List<Player> data = new List<Player>();

        string jsondata = File.ReadAllText(path);         
        data = JsonConvert.DeserializeObject<List<Player>>(jsondata);

        return data;
    }

    ^^ This method reads in the data.

    private string playerdata = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "playerdata.json");

    private string teamdata = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "team.json");

    ^^ These are the file paths used to read in the data.

    /// <summary>
    /// Method to write JSON data to a specified file.
    /// </summary>
    /// <param name="path"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    private void WriteFile(string path, List<Player> data)
    {
        string json = JsonConvert.SerializeObject(data, Formatting.Indented);
        File.WriteAllText(path, json);
    }

    ^^ Here is the method which rights to files.

【问题讨论】:

  • 您需要弄清楚为什么在写入 SpecialFolders.Personal 时会出现异常。请发布您的代码的相关部分
  • @Jason 我现在为你提供了一些代码 sn-ps。
  • File.Create(path).Dispose(); 所以你创建了一个空文件?这将从 DeserializeObject 返回一个空值。您在哪里/何时从本机资产复制文件?
  • @SushiHangover 文件需要为空才能开始,这是一个玩家可以输入队友姓名的应用程序。该应用程序未附带初始值。有什么想法吗?
  • @JamesTheHunt 您在哪里写入文件?

标签: c# json xamarin xamarin.forms xamarin.android


【解决方案1】:

试试这个 - 你不需要显式创建文件,File.WriteAllText() 应该为你做这个

private List<Player> ReadFile(string path)
{
    List<Player> data = new List<Player>();

    if (File.Exists(path))
    {
      string jsondata = File.ReadAllText(path);         
      data = JsonConvert.DeserializeObject<List<Player>>(jsondata);
    }

    return data;
}

【讨论】:

    【解决方案2】:

    所以...我只是通过更多的调试来修复它。问题是当我创建空白文件时,它没有 json 所需的 []。所以它返回null。

    我修复它的方法是添加应用程序设计的一个播放器,因此它有一个初始 JSON 对象来反序列化或序列化。

    感谢大家的帮助!

    【讨论】:

      猜你喜欢
      • 2016-08-15
      • 2018-11-07
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      相关资源
      最近更新 更多