xamarinandroidアプリケーションのWebサーバーからAPIにアクセスする

Joshua Chioma

APIからの結果をtextviewオブジェクトに解析する際に問題が発生しました...助けが必要です:

{"items":[{"id":0,"shortname":"NETD","_links":{"self":{"href":"http://api.iolab.net/v1/exams/0"}}}]

これが私のコードです:

Protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);

    // Get our button from the layout resource,
    // and attach an event to it
    //EditText latitude = FindViewById<EditText>(Resource.Id.editText1);
    EditText latitude = FindViewById<EditText>(Resource.Id.editText1);
    Button button = FindViewById<Button>(Resource.Id.button1);
    button.Click += async (sender, e) =>
    {
        string url = "http://api.iolab.net/v1/exams?";

        // Fetch the information asynchronously, parse the results,
        // then update the screen:
        JsonValue json = await FetchExamAsync(url);
        ParseAndDisplay(json);
    };

}

private async Task<JsonValue> FetchExamAsync(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));
            Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());

            // Return the JSON document:
            return jsonDoc;
        }

    } 
}

private void ParseAndDisplay(JsonValue json)
{

    TextView id = FindViewById<TextView>(Resource.Id.textView1);
    TextView Shortname = FindViewById<TextView>(Resource.Id.textView2);
    TextView links = FindViewById<TextView>(Resource.Id.textView3);

    // Extract the array of name/value results for the field name "item":
    // Note that there is no exception handling for when this field is not found.
    JsonValue Results = json["items"];
    id.Text = Results["id"];

    Shortname.Text = Results["shortname"];
    links.Text = Results["_links"];

}
OrcusZ

.NETアプリケーション(Xamarinを含む)でjsonを解析する最良の方法は、Newtonsoftnugetパッケージとhttp://json2csharp.com/Webサイトを使用することだと思います。

Xamarinアーキテクチャに準拠していない場合でも、非同期呼び出しをポータブルライブラリに配置してください。これは、このコースがすべてのプラットフォームで使用できるためです。

ここにnewtosoftの例があります:

//generated with json2csharp
//each class correspond to the json string retrieve by the back end

//{"href":"http://api.iolab.net/v1/exams/0"}
public class Self
{
    public string href { get; set; }
}

//"_links":{"self":{"href":"http://api.iolab.net/v1/exams/0"}
public class Links
{
    public Self self { get; set; }
}

//{"items":[{"id":0,"shortname":"NETD","_links":{"self":{"href":"http://api.iolab.net/v1/exams/0"}}}]}
public class Item
{
    public int id { get; set; }
    public string shortname { get; set; }
    public Links _links { get; set; }
}

//Rott object
public class RootObject
{
    public List<Item> items { get; set; }
}

jsonをアイテムに解析するには:

//json is the json string retrieve from the backend
//this method will convert the json to an item object if is possible
var item = JsonConvert.DeserializeObject<Item>(json);

アイテムのリストを解析するには:

//json is the json string retrieve from the backend
//this method will convert the json to a list of item object if is possible
var listitem =JsonConvert.DeserializeObject<List<Item>>(json);

WebサービスからGETメソッドを呼び出すためのジェネリックメソッドも提供します。

 //param is a get parameter and i actually optional
 public static async Task<String> RunGetAsync(string param = "")
        {
            HttpResponseMessage response = null;
            string url = "http://api.iolab.net/v1;
            string path = "/exam";
            //try catch can be deleted, i use it for timeout, task issues or web issues.
            try
            {
                using (var client = new HttpClient())
                {   
                    //create a client based in webservice url 
                    client.BaseAddress = new Uri(url);

                    client.DefaultRequestHeaders.Accept.Clear();
                    //timeout to call the backend
                    client.Timeout = TimeSpan.FromSeconds(10);
                    //if request is not allowAnonymous

                    //adding request header
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //to create a specific path for the call
                    if (string.IsNullOrEmpty(param))
                    {
                        response = await client.GetAsync(path);
                    }
                    else
                    {
                        response = await client.GetAsync(Path + "/" + param);
                    }

                    //check if the call succeed
                    if (response.IsSuccessStatusCode)
                    {
                        //get the response into string content & return it
                        var stringContent = await response.Content.ReadAsStringAsync();
                        return stringContent;

                    }

                    return null;
                }
            }
            catch (TaskCanceledException e)
            {
                Debug.WriteLine(e.Message);
                return null;
            }
            catch (WebException we)
            {
                Debug.WriteLine(we.Message);
                return null;
            }

}

ご不明な点がございましたら、この投稿にコメントすることを躊躇しないでください

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

WebアプリケーションからHDFSにアクセスする

分類Dev

別のサーバー上のPHPスクリプトからアプリケーションに投稿する

分類Dev

xamppのmysqlサーバーを外部に配置せずにJavaアプリケーションからデータベースにアクセスする方法

分類Dev

サーバーの外部IPアドレスからSpring Bootアプリケーションにアクセスできるようにする方法は?

分類Dev

ホストからコンテナのWebアプリケーションにアクセスする方法

分類Dev

LinuxサーバーのJavaWebアプリケーションからローカルパスにアクセスする方法は?

分類Dev

QML内からアプリケーションバージョンにアクセスする

分類Dev

Webアプリケーションから自分のAPIに安全にアクセスするにはどうすればよいですか?

分類Dev

C#アプリケーションから別のアプリケーションのメニューバーとサブメントにアクセスするにはどうすればよいですか?

分類Dev

JavaでhttpsからWebアプリケーションにアクセスできるようにする方法

分類Dev

SpringBootアプリケーションからSessionFactoryにアクセスする

分類Dev

.NetWebアプリケーションからIBMInformixにアクセスする

分類Dev

Webアプリケーションからデータベースにアクセスするためのベストプラクティス

分類Dev

Webブラウザ(Javascript)からクレデンシャルにアクセスするGoogleドライブAPIアプリケーションデータ

分類Dev

別のサブネットでWebアプリケーションにアクセスする方法は?

分類Dev

postfixを含むサーバーにアクセスし、それを使用してSpring Bootアプリケーションからメールを送信する

分類Dev

別のマシンのJSFアプリケーションからEJBにアクセスする方法

分類Dev

別のアプリケーションから呼び出されたWebサービスのweb.configセクションにアクセスするにはどうすればよいですか?

分類Dev

「このWebサイトから次のアプリケーションへのアクセスを許可する」プロンプト-Java

分類Dev

クラスタ外のアプリケーションからkubernetesのpostgresにアクセスする

分類Dev

Webアプリケーションアクセス用の自宅のプロキシサーバー

分類Dev

UNIXサーバーにアクセスし、Javaアプリケーションからシェルスクリプトを実行します

分類Dev

HTML / Angularアプリケーションからモバイルカメラにアクセスする

分類Dev

バックエンドサーバープロセスからアプリケーションをウェイクアップする方法は?

分類Dev

Windows10ユニバーサルアプリケーションからのSQLアクセス

分類Dev

モバイル アプリケーションから AWS Elasticsearch へのアクセスを保護する方法

分類Dev

PHP Web アプリケーションを商用サーバーからローカル XAMPP に移行する

分類Dev

外部アプリケーションからSymfonyセッション値にアクセスする

分類Dev

android-roomからサードパーティアプリケーションのデータにアクセスする可能性

Related 関連記事

  1. 1

    WebアプリケーションからHDFSにアクセスする

  2. 2

    別のサーバー上のPHPスクリプトからアプリケーションに投稿する

  3. 3

    xamppのmysqlサーバーを外部に配置せずにJavaアプリケーションからデータベースにアクセスする方法

  4. 4

    サーバーの外部IPアドレスからSpring Bootアプリケーションにアクセスできるようにする方法は?

  5. 5

    ホストからコンテナのWebアプリケーションにアクセスする方法

  6. 6

    LinuxサーバーのJavaWebアプリケーションからローカルパスにアクセスする方法は?

  7. 7

    QML内からアプリケーションバージョンにアクセスする

  8. 8

    Webアプリケーションから自分のAPIに安全にアクセスするにはどうすればよいですか?

  9. 9

    C#アプリケーションから別のアプリケーションのメニューバーとサブメントにアクセスするにはどうすればよいですか?

  10. 10

    JavaでhttpsからWebアプリケーションにアクセスできるようにする方法

  11. 11

    SpringBootアプリケーションからSessionFactoryにアクセスする

  12. 12

    .NetWebアプリケーションからIBMInformixにアクセスする

  13. 13

    Webアプリケーションからデータベースにアクセスするためのベストプラクティス

  14. 14

    Webブラウザ(Javascript)からクレデンシャルにアクセスするGoogleドライブAPIアプリケーションデータ

  15. 15

    別のサブネットでWebアプリケーションにアクセスする方法は?

  16. 16

    postfixを含むサーバーにアクセスし、それを使用してSpring Bootアプリケーションからメールを送信する

  17. 17

    別のマシンのJSFアプリケーションからEJBにアクセスする方法

  18. 18

    別のアプリケーションから呼び出されたWebサービスのweb.configセクションにアクセスするにはどうすればよいですか?

  19. 19

    「このWebサイトから次のアプリケーションへのアクセスを許可する」プロンプト-Java

  20. 20

    クラスタ外のアプリケーションからkubernetesのpostgresにアクセスする

  21. 21

    Webアプリケーションアクセス用の自宅のプロキシサーバー

  22. 22

    UNIXサーバーにアクセスし、Javaアプリケーションからシェルスクリプトを実行します

  23. 23

    HTML / Angularアプリケーションからモバイルカメラにアクセスする

  24. 24

    バックエンドサーバープロセスからアプリケーションをウェイクアップする方法は?

  25. 25

    Windows10ユニバーサルアプリケーションからのSQLアクセス

  26. 26

    モバイル アプリケーションから AWS Elasticsearch へのアクセスを保護する方法

  27. 27

    PHP Web アプリケーションを商用サーバーからローカル XAMPP に移行する

  28. 28

    外部アプリケーションからSymfonyセッション値にアクセスする

  29. 29

    android-roomからサードパーティアプリケーションのデータにアクセスする可能性

ホットタグ

アーカイブ