C#WebRequest返回JSON值,使用随机输出结果的输出量



我正在使用猫事实API进行一些有趣的练习。我遇到的问题不是一次显示一个随机的"猫事实"。但是我试图显示多达五个总数的随机事实。例如,用户单击该按钮获取3个事实,用户再次单击按钮并获得1个事实,用户第三次单击按钮,然后获得1、2、3、4或5个事实。我试图在一个活动/班级中完成所有操作。http://catfacts-api.appspot.com/api/facts?number=5将显示5个事实,http://catfacts-api.appspot.com/api/facts将返回一个事实。这就是我的代码到目前为止的外观,

public class MainActivity : Activity
{
private ImageButton _mrWhiskersButton;
private TextView _catFactsTextView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        _mrWhiskersButton = FindViewById<ImageButton>(Resource.Id.imageCatButton);
        _catFactsTextView = FindViewById<TextView>(Resource.Id.catFactsText);
        _mrWhiskersButton.Click += async delegate
        {

            string url = "Http://catfacts-api.appspot.com/api/facts";
            JsonValue json = await FetchInfoAsync(url);
            updateCats(json);
        };
    }
    public async Task<JsonValue> FetchInfoAsync(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Method = "GET";
        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                JsonValue jsonDoc = await Task.Run(() => JsonValue.Load(stream));
                Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                return jsonDoc;
            }
        }
    }
    private void updateCats(JsonValue json)
    {
        _catFactsTextView.Text = json["facts"][0];
    }
}
}
public class MainActivity : Activity
{
  private ImageButton _mrWhiskersButton;
  private TextView _catFactsTextView;
  private System.Random rand;
  protected override void OnCreate(Bundle bundle)
  {
    base.OnCreate(bundle)
    rand = new System.Random();
    // omitted code...
    _mrWhiskersButton.Click += async delegate
    {
        // get next random int between 1 and 5
        int ndx = rand.Next(1,5);
        string url = $"Http://catfacts-api.appspot.com/api/facts?number={ndx}";
        JsonValue json = await FetchInfoAsync(url);
        updateCats(json);
    };
}
  private void updateCats(JsonValue json)
  {
      foreach (var fact in json["facts"]) {
        _catFactsTextView.Text += fact + "n";          
      }
  }

相关内容

  • 没有找到相关文章

最新更新