私はこの記事http://www.dotnetcurry.com/showarticle.aspx?ID=1029をフォローしていて、誰かがボタンをクリックした後にAndroidでリストを表示するためにRESTapiからjsonを抽出しようとしています。私のjsonは次のようになります。
[{"id":"1","name":"test","address":"test","country":"usa"},{"id":"2","name":"test1","address":"test1","country":"uk"}]
これはHackerNewsRepository.csの私のコードクラスファイルです
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Shared
{
public class HackerNewsRepository
{
public async Task<IEnumerable<Entry>> TopEntriesAsync()
{
var client = new HttpClient();
var result = await client.GetStringAsync("http://www.example.com/api/v1/info");
return JsonConvert.DeserializeObject<Entry>(result);
}
}
public class Entry
{
public int Id { get; set; }
public string Names { get; set; }
public string Address { get; set; }
public string Country { get; set; }
}
}
App.csのクラスファイル
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Shared;
namespace DNC.NewsReader
{
public class HackerNewsPage : ContentPage
{
private ListView listView;
public HackerNewsPage()
{
Title = "Hacker News Stories";
listView = new ListView
{
RowHeight = 80
};
Content = new StackLayout
{
VerticalOptions = LayoutOptions.FillAndExpand,
Children = { listView }
};
}
protected override async void OnAppearing()
{
base.OnAppearing();
var entries = await new HackerNewsRepository().TopEntriesAsync();
listView.ItemTemplate = new DataTemplate(typeof(HackerNewsEntryCell));
listView.ItemsSource = entries;
}
}
public class HackerNewsEntryCell : ViewCell
{
public HackerNewsEntryCell()
{
var id = new Label();
id.SetBinding(Label.TextProperty, "Id");
var name = new Label();
name.SetBinding(Label.TextProperty, "Name");
var grapes = new Label();
grapes.SetBinding(Label.TextProperty, "Address");
var country = new Label();
country.SetBinding(Label.TextProperty, "Country");
View = new StackLayout
{
Children = {Id, Name, Address, Country}
};
}
}
public class App
{
public static INavigation Navigation { get; private set; }
public static Xamarin.Forms.Page GetMainPage()
{
var navigationPage = new NavigationPage(new HackerNewsPage());
Navigation = navigationPage.Navigation;
return navigationPage;
}
}
}
これはメインアクティビティクラスファイルです
using Xamarin.Forms.Platform.Android;
...
namespace DNC.NewsReader.Droid
{
[Activity(Label = "DNC.NewsReader", MainLauncher = true)]
public class MainActivity : AndroidActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
SetPage(App.GetMainPage());
}
}
}
問題はdeserializeObject
部分的にあり、また私はネットで与えられた異なるロジックの例を適用しましたが、できませんでした、与えられたjsonフォーマットからアンドロイドで出力を与えるのを手伝ってください。ありがとうございました!
あなたがすべき :
return JsonConvert.DeserializeObject<IEnumerable<Entry>>(result);
必要に応じて、Entry
クラス属性に小文字を使用して、JSON文字列と同じになるようにしてください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加