我一直在教程,使Web服務從URL獲取數據。但是,在教程中,它要求添加System.Json。我添加了使用System.Json,但它給了我一個錯誤。Xamarin添加System.Json
//這裏是我在C#中已經完成了代碼,它工作得很好
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft;
using Newtonsoft.Json;
namespace Weather_App
{
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://api.wunderground.com/api/key/conditions/q/CA/Houston.json");
WebRequest webRequest = WebRequest.Create(uri);
WebResponse response = webRequest.GetResponse();
StreamReader stramreader = new StreamReader(response.GetResponseStream());
String responseData = stramreader.ReadToEnd();
var outObject = JsonConvert.DeserializeObject<Component.RootObject>(responseData);
Console.WriteLine(responseData);
Console.ReadLine();
}
}
}
//這裏是我想實現在Xamarin相同的功能的代碼,但在使用有困難system.json
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Xamarin.Forms;
using System.Xml;
using System.Json;
namespace Exercise21
{
public partial class MyPage : ContentPage
{
public MyPage()
{
InitializeComponent();
CallWebService();
}
private async void CallWebService()
{
Uri url = new Uri ("http://api.wunderground.com/api/key/conditions/q/CA/Houston.json");
var httpReq = (HttpWebRequest)HttpWebRequest.Create (url);
httpReq.BeginGetResponse ((ar) => {
var request = (HttpWebRequest)ar.AsyncState;
using (var response = (HttpWebResponse)request.EndGetResponse (ar)) {
var s = response.GetResponseStream();
var j = (JsonObject)JsonObject.Load (s);
var results = (from result in (JsonArray)j ["results"]
let jResult = result as JsonObject
select jResult ["text"].ToString()).ToArray();
RunOnUiThread (() => {
ListAdapter = new ArrayAdapter<string> (this,
Resource.Layout.TweetItemView, results);
});
}
}, httpReq);
}
}
}
你有沒有引用相關的程序集? Xamarin中的組件與常規.Net中的組件略有不同。 [此鏈接](http://developer.xamarin.com/guides/android/under_the_hood/assemblies/)可能會有所幫助。 – 2014-10-07 20:04:12
我願意讓你使用Json.NET。這是一個圖書館,你可以在nuget上找到 – Pedro 2014-10-07 20:05:29
另外,如果你的教程是在線的,在你的問題中加入一個鏈接可能會有所幫助。它實際上是一個Xamarin教程嗎? – 2014-10-07 20:10:23