Xamarin調用JSON.net來解析JSON
阿新 • • 發佈:2017-12-07
bsp blank ebo sof .html www label nts 測試
- https://www.cnblogs.com/zjoch/p/4458516.html
-
再來我們要怎麽解析JSON格示呢?在.net 中,我們很孰悉的JSON.net,沒錯,我們依然可以在Xamarin中使用他
感謝社群偉大的貢獻 下載網址: http://components.xamarin.com/view/json.net/
接續上一個項目我們多引入下載後的 Newtonsoft.Json.dll
記得要引入Android 下的
引入後就跟我們平常使用JSON.net 一樣首先我們要為Facebook接回來的數據建立一個相對應的Class
這時候我們可以使用 http://json2csharp.com/ 這網站幫忙
在項目中建立一個User 的Class
01.
namespace
SampleForWebClient
02.
{
03.
public
class
User
04.
{
05.
public
string
id {
get
;
set
; }
06.
public
string
name {
get
;
set
; }
07.
public
string
first_name {
get
;
set
; }
08.
public
string
last_name {
get
;
set
; }
09.
public
string
link {
get
;
set
; }
10.
public
string
username {
get
;
set
; }
11.
public
string
gender {
get
;
set
; }
12.
public
string
locale {
get
;
set
; }
13.
}
14.
}
我們回到主程序
01.
using
<a href=
"http://www.it165.net/pro/ydad/"
target=
"_blank"
class
=
"keylink"
>Android</a>.App;
02.
using
Android.Widget;
03.
using
Android.OS;
04.
using
Newtonsoft.Json;
05.
06.
namespace
SampleForWebClient
07.
{
08.
[Activity(Label =
"Json.net測試"
, MainLauncher =
true
, Icon =
"@drawable/icon"
)]
09.
public
class
Activity1 : Activity
10.
{
11.
protected
override
void
OnCreate(Bundle bundle)
12.
{
13.
base
.OnCreate(bundle);
14.
15.
// Set our view from the "main" layout resource
16.
SetContentView(Resource.Layout.Main);
17.
18.
var btnGetData1 = FindViewById<Button>(Resource.Id.btnGetData1);
19.
20.
btnGetData1.Click += btnGetData1_Click;
21.
}
22.
23.
void
btnGetData1_Click(
object
sender, System.EventArgs e)
24.
{
25.
var webClient =
new
System.Net.WebClient();
26.
var result = webClient.DownloadString(
"https://graph.facebook.com/donma.hsu"
);
27.
//透過JSON.net 反序列化為User對象
28.
var user = JsonConvert.DeserializeObject<User>(result);
29.
//印出 id and name
30.
Toast.MakeText(
this
, user.id+
":"
+user.name, ToastLength.Long).Show();
31.
}
32.
33.
34.
}
35.
}
結果:
是不是很簡單,在Xamarin 下面開發Android 跟過去的體驗是相同的
Xamarin調用JSON.net來解析JSON