【问题标题】:Parsing downloaded JSON file from github in c# uwp在 c# uwp 中解析从 github 下载的 JSON 文件
【发布时间】:2016-01-12 18:23:54
【问题描述】:

这是我从 GitHub 下载的:https://gist.githubusercontent.com/Keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.jsonhttps://raw.githubusercontent.com/dominictarr/random-name/master/first-names.json

我的应用程序中有两个文本块,我想检查输入的国家名称和名字是否存在于列表中。

我希望应用程序处于脱机状态,因此我下载了这些文件。 JSON 真的很新。

还有其他选项可以填充名称国家等列表吗?

更新:我已经尝试了很多东西,包括下面马修回答中的代码。但我收到以下消息

Name Place Animal Thing.exe 中 0x75A86ABE (combase.dll) 处未处理的异常:0xC000027B:发生了应用程序内部异常(参数:0x097EF758、0x00000002)。

我尝试过这样的事情:

 private void newbt_Click(object sender, RoutedEventArgs e)
    {
        List<Places> myPlaces = JsonConvert.DeserializeObject<List<Places>>("Assets/countries.json");
        bool zimbabwe = myPlaces.Any(x => x.name == "Zimbabwe");
        if (zimbabwe)
            NTB.Text = "";

    }

【问题讨论】:

  • 查看:json.net,他们的文档中有一些教程可能会对您有所帮助。
  • 您的问题是什么?无法理解您想要什么。

标签: c# json xaml


【解决方案1】:

JSON.net 是我所知道的用于处理 json 的最佳工具。使用 nuget 将 json.net 添加到您的项目中,然后您可以将 json 转换为如下列表:

List<Country> countries = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>>(json);

这要求您在项目中定义此类:

public class Country
{
    public string name { get; set; }
    public string code { get; set; }
}

您可以使用带有 lambda 表达式的 linq 检查该国家/地区是否在列表中:

        bool zimbabwe = countries.Any(x=>x.name=="Zimbabwe");//true
        bool fakecountry = countries.Any(x => x.name == "fake");//false

回答你的问题

还有其他选项可以填充名称国家等列表吗?

是的,还有其他选择。 JSON.net 还支持JSONPath,它基本上是 XPath 的副本,但用于 JSON 而不是 XML。不过,您可能会遇到麻烦,因为您的 json 看起来不是有效的 json(属性名称应该用引号括起来:{'name':'Zimbabwe','code':'ZW'}

【讨论】:

  • 我收到未处理的异常消息。请参阅帖子中的更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2021-02-01
  • 2017-08-15
  • 1970-01-01
相关资源
最近更新 更多