【问题标题】:how to fix file .json not found when it is there如何修复文件.json在存在时找不到
【发布时间】:2020-11-29 08:00:46
【问题描述】:

我在这里尝试使用 json 文件中的数据: 数据.json

[

{"Label"
        
        :"USA",
        "Adress":"This is the us",
        "Lat":"36.9628066",
        "Lng":"-122.0194722"
},
{ "Label"  :"USA",
         "Address":"2020",
          "Lat":"36.9628066", 
          "Lng":"-122.0194722" }

]

然后在我的 Mainclass 中应用它:

using System.Collections.Generic;
using Xamarin.Forms.Maps;
using Xamarin.Forms;
using System.IO;
using Newtonsoft.Json;
using System;


namespace Orbage
{
    

class MapPage : ContentPage
    {
        public MapPage()
        {
            CustomMap customMap = new CustomMap
            {
                MapType = MapType.Street

            };
            // ...
            Content = customMap;

            var json = File.ReadAllText("File.json");
            var places = JsonConvert.DeserializeObject<List<File>>(json);
            foreach (var place in places)
            {
                CustomPin pin = new CustomPin
                {
                    Type = PinType.Place,
                    Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
                    Label = place.Label,
                    Address = place.Address,
                    Name = "Xamarin",

                    Url = "http://xamarin.com/about/"
                };



                customMap.CustomPins = new List<CustomPin> { pin };

                customMap.Pins.Add(pin);
                customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
            }
        }
    }


}

但是当我把文件放在那里时,它说它不存在。 错误: FilenotfoundException 有什么办法解决这个问题。 我试过了: 更改文件的位置。 其名称 而不是 E:/-/- 我什至写了 file.json 但我仍然得到同样的错误。 非常感谢!

【问题讨论】:

  • 使用 ApplicationContext.GetExternalFilesDirs(null) 获取应用的内部和外部目录列表并将其添加到文件名之前。
  • 请你用一点代码解释一下。我不明白你在文件名前加上它是什么意思。
  • json文件的全路径和Mainclass的全路径是什么?
  • 它的这个 C:\Users\----\source\repos\-----\-----\------\DATA.json
  • 您将文件添加到哪个项目?

标签: java c# xamarin


【解决方案1】:

尝试使用以下方法:

将您的File.json 放入您的PCL 项目,并将其Build Action 设置为EmbeddedResource

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MapPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("Orbage.File.json");
string text = "";
using (var reader = new System.IO.StreamReader(stream))
     {
       text = reader.ReadToEnd();
     }

【讨论】:

  • @ItsRaptorman 替换 var json = File.ReadAllText("File.json");
  • 是的,我确实这样做了。但是在这个 var 地方 = JsonConvert.DeserializeObject>(json);当我确实替换了 json 和 DATA 有错误时。
  • @ItsRaptorman 什么错误?让我们谈谈here
【解决方案2】:

最好在读取文件之前先检查文件是否存在于该位置。

if (File.Exists("File.Json"))

这样你就会知道你给定的路径是否正确。

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多