1.新建一个Android项目,并命名为为NetJsonList
2.右击引用,选择添加引用,引用System.Json.dll
二、同步请求
既然是跨平台,我们自然不能按照java下的方式进行编写,否则如何跨平台呢,所以我们需要使用Syste.Net命名空间下的两个类:HttpWebRequest和HttpWebResponse。
首先打开Resources/layout/Main.axml文件
删除其他上面的控件,并拖拽一个Text(large)到其中。
接着打开MainActivity.cs文件,并将如下代码写入其中
1 namespace NetJsonList 2 { 3 [Activity(Label = "NetJsonList", MainLauncher = true, Icon = "@drawable/icon")] 4 public class MainActivity : Activity 5 { 6 TextView tv; 7 8 protected override void OnCreate(Bundle bundle) 9 { 10 base.OnCreate(bundle); 11 SetContentView(Resource.Layout.Main); 12 13 tv = FindViewById<TextView>(Resource.Id.textView1); 14 15 LoadXamarin(); 16 } 17 18 public void LoadXamarin() 19 { 20 //测试用 21 string url = "http://www.xamarin-cn.com/test.json"; 22 23 //创建一个请求 24 var httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); 25 26 //获取响应 27 var httpRes = (HttpWebResponse)httpReq.GetResponse(); 28 29 //读取响应的字符串 30 String text = new StreamReader(httpRes.GetResponseStream()).ReadToEnd(); 31 tv.Text = text; 32 } 33 } 34 }