【问题标题】:Downloading info from JSON(Xamarin C#)从 JSON 下载信息(Xamarin C#)
【发布时间】:2016-08-06 14:10:11
【问题描述】:

我正在用 Xamarin C# 编写 Android 应用程序。

我从 JSON 中解析信息,然后将其显示在字段中。

我使用这个代码:

string url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
        JsonValue json = await FetchAsync(url2);
 private async Task<JsonValue> FetchAsync(string url)
    {
        // Create an HTTP web request using the URL:
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Method = "GET";

        // Send the request to the server and wait for the response:
        using (WebResponse response = await request.GetResponseAsync())
        {
            // Get a stream representation of the HTTP web response:
            using (Stream stream = response.GetResponseStream())
            {
                // Use this stream to build a JSON document object:
                JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
                //dynamic data = JObject.Parse(jsonDoc[15].ToString);
                Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());


                // Return the JSON document:
                return jsonDoc;
            }
        }
    }

但我有一个问题。当我打开 Activity 时,它会冻结 2-3 秒,然后所有信息都会显示在字段中。

我能否顺利下载该数据。第一个字段,然后是第二个字段,以此类推。

如果可以的话,怎么做?

【问题讨论】:

  • 这适用于 Java。我使用 C# @AllLelopath
  • 显示您如何调用FetchAsync 并在您的视图中设置值。
  • 你在哪里调用 FetchAsync?在事件处理程序中还是在哪里?能否提供更多信息?

标签: c# android json xamarin xamarin.android


【解决方案1】:

我建议在 C# 中实现 async/await 的正确用法,并切换到 HttpClient,它也实现了 async/await 的正确用法。下面是一个代码示例,它将在 UI 线程之外检索您的 Json:

var url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
var jsonValue = await FetchAsync(url2);

private async Task<JsonValue> FetchAsync(string url)
{
   System.IO.Stream jsonStream;
   JsonValue jsonDoc;

   using(var httpClient = new HttpClient())
   {
     jsonStream = await httpClient.GetStreamAsync(url);
     jsonDoc = JsonObject.Load(jsonStream);
   }

   return jsonDoc;
}

如果您在 Android 项目中编写代码,则需要添加 System.Net.Http DLL 作为参考。如果您在 aPCL 中编写代码,则需要安装 Microsoft Http Client Libraries Nuget Package。为了提高性能,我推荐使用ModernHttpClient,它也可以从 Nuget 安装。

【讨论】:

    【解决方案2】:

    您在 HttpWebRequest 中的 Async-Await 用法是正确的。从 Activity 错误调用此方法可能会导致 UI 冻结。我将在下面解释如何调用。

    我还建议使用 ModernHttpClient 库来加速 API 调用。

    public static async Task<ServiceReturnModel> HttpGetForJson (string url)
        {
    
            using (var client = new HttpClient(new NativeMessageHandler())) 
            {
    
                try
                {
                    using (var response = await client.GetAsync(new Uri (url))) 
                    {
                        using (var responseContent = response.Content) 
                        {
                            var responseString= await responseContent.ReadAsStringAsync();
                            var result =JsonConvert.DeserializeObject<ServiceReturnModel>(responseString);
                        }
                    }
                }
                catch(Exception ex) 
                {
                   // Include error info here
                }
                return result;
    
            }
    
        }
    

    您需要包含 Xamarin 组件 ModernHttpClient 和 JSON.NET (Newtonsoft.Json)

    在不阻塞 UI 的情况下从 Activity 调用此方法

    protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
    
            SetContentView (Resource.Layout.Main);
            // After doing initial Setups
            LoadData();
         }
    
    // This method downloads Json asynchronously without blocking UI and without showing a Pre-loader.
    async Task LoadData()
        {
            var newRequestsResponse =await ServiceLayer.HttpGetForJson (newRequestsUrl);
          // Use the data here or show proper error message
        }
    
     // This method downloads Json asynchronously without blocking UI and shows a Pre-loader while downloading.
    async Task LoadData()
        {
            ProgressDialog progress = new ProgressDialog (this,Resource.Style.progress_bar_style);
            progress.Indeterminate = true;
            progress.SetProgressStyle (ProgressDialogStyle.Spinner);
            progress.SetCancelable (false);
            progress.Show ();
            var newRequestsResponse =await ServiceLayer.HttpGetForJson (newRequestsUrl);
            progress.Dismiss ();
          // Use the data here or show proper error message
        }
    

    材质类型加载器样式。包含在 Resources/Values/Style.xml 中

    <style name="progress_bar_style">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:background">@android:color/transparent</item>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多