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"];
}
.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]
コメントを追加