【问题标题】:Downloading JSON in UWP (C#)在 UWP 中下载 JSON (C#)
【发布时间】:2016-05-07 10:29:26
【问题描述】:

我是 UWP 平台开发的新手。

我正在为 Windows 10 移动版编写 UWP 应用。

我是这样下载的

public async Task<string> FetchAsync(string url)
{
    string jsonString;

    using (var httpClient = new System.Net.Http.HttpClient())
    {
        var stream = await httpClient.GetStreamAsync(url);
        StreamReader reader = new StreamReader(stream);
        jsonString = reader.ReadToEnd();
    }

    return jsonString;
}

像这样写入文件:

  string url = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=82";
        var json = await FetchAsync(url);
        using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
        {
            json.Save(fs);
        }

        Debug.WriteLine(json);

完整代码:

  using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using System.Xml;
using Windows.ApplicationModel.Calls;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace  Murakami
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public  sealed  partial class   MainPage : Page
    {
        public MainPage()
        {




            string url = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=82";
            var json = await FetchAsync(url);
            using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
            {
                json.Save(fs);
            }

            Debug.WriteLine(json);


            this.InitializeComponent();
            XmlDocument doc = new XmlDocument();
            XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Order"));
            el.SetAttribute("CallConfirm", "1");
            el.SetAttribute("PayMethod", "");
            el.SetAttribute("QtyPerson", "");
            el.SetAttribute("Type", "1");
            el.SetAttribute("PayStateID", "0");
            el.SetAttribute("Remark", "{StreetName} , ..");
            el.SetAttribute("RemarkMoney", "0");
            el.SetAttribute("TimePlan", "");
            el.SetAttribute("Brand", "1");
            el.SetAttribute("DiscountPercent", "0");
            el.SetAttribute("BonusAmount", "0");
            el.SetAttribute("Department", "");

            XmlElement el2 = (XmlElement)el.AppendChild(doc.CreateElement("Customer"));

            el2.SetAttribute("Login", "");
            el2.SetAttribute("FIO", "{FIO}");

            XmlElement el3 = (XmlElement)el.AppendChild(doc.CreateElement("Address"));

            el3.SetAttribute("CityName", "");
            el3.SetAttribute("StationName", "");
            el3.SetAttribute("StreetName", "{StreetName}");
            el3.SetAttribute("House", "{HouseName}");
            el3.SetAttribute("Corpus", "");
            el3.SetAttribute("Building", "");
            el3.SetAttribute("Flat", "{FlatName}");
            el3.SetAttribute("Porch", "");
            el3.SetAttribute("Floor", "");
            el3.SetAttribute("DoorCode", "");

            XmlElement el4 = (XmlElement)el.AppendChild(doc.CreateElement("Phone"));

            el4.SetAttribute("Code", "{Code}");
            el4.SetAttribute("Number", "{Phone}");

            XmlElement el5 = (XmlElement)el.AppendChild(doc.CreateElement("Products"));




              using (FileStream fs = new FileStream("test.xml", FileMode.Create))
              {
                  doc.Save(fs);
              }

              Debug.WriteLine(doc);







        }

       async private void TwitterButton_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://twitter.com/murakami_rest"));

        }

       async private void FacebookButton_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://www.facebook.com/MURAKAMI.rest"));
        }

       async  private void button9_Click_1(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://vk.com/murakami_restaurant_delivery"));
        }

        async private void InstagramButton_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://instagram.com/murakami_in_ua/"));

        }

        private void PhoneCallButton_Click(object sender, RoutedEventArgs e)
        {
            PhoneCallManager.ShowPhoneCallUI("+380442308888","");
        }

        private void ProMurakamiButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(ProMurakami));

        }

        private void BludoDnyaButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(BludoDnya));
        }

        private void CartButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Cart2));
        }


        /* private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
         {
             PhoneCallManager.ShowPhoneCallUI("0213132131", "my name");
         }*/
    }




   public async Task<string> FetchAsync(string url)
    {
        string jsonString;

        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        return jsonString;
    }
}

我有这些错误:

 Error  CS0116  A namespace cannot directly contain members such as fields or methods



 Error  CS0103  The name 'FetchAsync' does not exist in the current context Murakami    



  Error CS4033  The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.    

我的代码错误在哪里?

非常感谢您的帮助!

【问题讨论】:

    标签: c# .net json xaml win-universal-app


    【解决方案1】:

    我看过你的代码。

    首先

    你在哪里:

    /* private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
         {
             PhoneCallManager.ShowPhoneCallUI("0213132131", "my name");
         }*/
    } // <-- This brace is closing off the class too early.
    

    最后一个大括号关闭了类,因此FetchAsync(url) 方法试图被声明为它自己的类。

    从这段代码之后删除有问题的},并将一个放在底部的右边。像这样:

                /* private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
             {
                 PhoneCallManager.ShowPhoneCallUI("0213132131", "my name");
             }*/
    
    
            public async Task<string> FetchAsync(string url)
            {
                string jsonString;
    
                using (var httpClient = new System.Net.Http.HttpClient())
                {
                    var stream = await httpClient.GetStreamAsync(url);
                    StreamReader reader = new StreamReader(stream);
                    jsonString = reader.ReadToEnd();
                }
    
                return jsonString;
            }
        } 
    } // <-- Add this one, right here
    

    这是导致你的

    错误 CS0116 命名空间不能直接包含字段或方法等成员

    错误 CS0103 当前上下文中不存在名称“FetchAsync”村上

    并且 其次

    你的await FetchAsync(url);调用在类的构造函数中,不能标记为async

    你需要创建一个新方法,包装你的

    var json = await FetchAsync(url);
                using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
                {
                    json.Save(fs);
                }
    
                Debug.WriteLine(json);
    

    在它自己的 async 方法中,然后从你的构造函数中调用它。

    像这样:

        private async void NewMethod(string url)
        {
            var json = await FetchAsync(url);
            using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
            {
                // Do stuff in here to write to your file...
            }
    
            Debug.WriteLine(json);
        }
    

    访问 https://msdn.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files 了解更多关于在 UWP 中将文本写入文件的信息。

    然后通过您的ctor 调用它...

    public MainPage() {
            string url = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=82";
            NewMethod(url); // Now call your newly-created method.
    
            ... // Do your other stuff as before.
    }
    

    这就是造成你的原因

    错误 CS4033 'await' 运算符只能在异步方法中使用。考虑使用“异步”修饰符标记此方法并将其返回类型更改为“任务”。

    希望这会有所帮助!如果您需要更多信息,请告诉我。

    【讨论】:

    • 有这个。错误 CS1061“字符串”不包含“保存”的定义,并且找不到接受“字符串”类型的第一个参数的扩展方法“保存”(您是否缺少 using 指令或程序集引用?)
    • 我实际上只是复制和粘贴代码;所以我没有仔细查看using (FileStream fs = ...) 方法中的json.Save 部分。您将需要删除它并写入您的文件流并保存它。我会更新我的答案并附上一个链接。
    • 我刚刚编辑了我的最后一条评论。您的代码正在尝试使用不存在的string 方法(json 是一个字符串)。您将需要改用fs 编写。我将在我的回答中包含如何执行此操作的链接。
    • msdn.microsoft.com/en-us/library/8bh11f1k.aspx 是另一个用于将文本写入文件的有用链接。
    【解决方案2】:

    让我们从头开始:

    错误 CS0116 命名空间不能直接包含字段或方法等成员

    您在某处遗漏了 { 或 } 符号(或者它们在错误的位置。如果您再次检查代码以确保大括号正确,那么第一个和第二个错误将消失。

    关于什么

    'await' 运算符只能在异步方法中使用...

    您应该在调用“await”操作的方法中使用“async”谓词。但我记得你不能让 coustructor 异步。因此,我可以建议您将代码放在 Loading 事件中,并为该事件添加异步谓词

    【讨论】:

    • 正确。我已经扩展并在我的答案中包含了示例:)(同时发布 - 伟大的思想等等......)
    【解决方案3】:

    您可以使用 GetAsync

     var response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        return await response.Content.ReadAsAsync<string>();
                    }
    

    标题命名空间:

    using System.Net.Http;
    using System.Net.Http.Headers;
    

    并以 json 字符串而不是 StreamReader 读取响应。

    【讨论】:

    • 谢谢,它帮助了我:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多