代码之家  ›  专栏  ›  技术社区  ›  user5677145

在UWP中下载JSON(C#)

  •  2
  • user5677145  · 技术社区  · 8 年前

    我是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'.    
    

    我的代码错误在哪里?

    非常感谢您的帮助!

    3 回复  |  直到 8 年前
        1
  •  3
  •   Geoff James    8 年前

    我看过你的代码了。

    首先

    您已经掌握了:

    /* 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”在当前上下文Murakami中不存在

    第二

    你的 await FetchAsync(url); 调用位于类的构造函数内,该类不能标记为 async .

    您需要创建一个新方法

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

    在其自身 异步 方法,然后从构造函数调用它。

    这样地:

        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”运算符只能在异步方法中使用。考虑使用“async”修饰符标记此方法,并将其返回类型更改为“Task”。

    希望这有帮助!如果你还需要什么,请告诉我。

        2
  •  0
  •   Alexej Sommer    8 年前

    让我们从头开始:

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

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

    关于什么

    “await”运算符只能在异步方法中使用。。。

    在调用“await”操作的方法中应该有“async”谓词。但正如我所记得的,您不能使coustrutor异步。因此,我建议您将代码放在Loading事件中,并将异步谓词添加到此事件中

        3
  •  0
  •   Dev-Systematix    8 年前

    您可以使用 获取异步

     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读取响应。