2016-04-14 4 views
3

私はXamarin C#でAndroidアプリを書いています。JSON(Xamarin C#)からの情報ダウンロード

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; 
      } 
     } 
    } 

をしかし、私は一つの問題があります。アクティビティを開くと2〜3秒間フリーズし、すべての情報がフィールドに表示されます。

データをスムーズにダウンロードできますか?最初のフィールド、次に秒など

もし私ができれば、どうですか?

+0

あなたがボレーを使用することができますが含まれるように、例えばhttp://www.androidhive.info/2014/09/android-json-parsing-using-volley/ –

+0

これはJava用です。 私はC#@AlLelopath –

+0

を使用しています。あなたは 'FetchAsync'をどのように呼び出すかを示し、あなたの値を設定します。 –

答えて

1

C#でasync/awaitを適切に実装し、async/awaitの適切な使い方を実装しているHttpClientに切り替えることをお勧めします。以下は、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でもインストールできます。

1

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; 

     } 

    } 

あなたはUI

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 
    } 

材質タイプLoaderのスタイルを遮断することなく、XamarinコンポーネントModernHttpClientとJSON.NET(Newtonsoft.Json)Activityからこのメソッドを呼び出す

を含める必要があります。 /リソース/値の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> 

関連する問題