Monotouch:将JSON从MVC反序列化为Montouch

Moj*_*oDK 2 model-view-controller json xamarin.ios

在我的测试vb.net MVC网络应用程序中,我有这个json ....

Public Class Person
    Public Property Name As String
    Public Property Age As Byte
    Public Sub New(name As String, age As Byte)
        Me.Name = name
        Me.Age = age
    End Sub
End Class

Function GetPerson() As JsonResult
    Dim p As New Person("John Doe", 50)
    Return Json(p, JsonRequestBehavior.AllowGet)
End Function
Run Code Online (Sandbox Code Playgroud)

在Monotouch我有这个......

JsonObject j;
Uri address = new Uri("http://mysite/home/GetPerson");
HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create (address);
using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse ()) {
    Stream s = httpRes.GetResponseStream ();
    j = (JsonObject)JsonObject.Load (s);
}
Run Code Online (Sandbox Code Playgroud)

而这堂课......

Public Class Person {
    Public string Name { get; set; }
    Public byte Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何将JsonObject j解析为Person类?..我希望像Person p =(Person)j.value;

谢谢!魔

Anu*_*nuj 5

首先,我会使用int作为Age.但假设JSON结构如下:

{   
    "Name" : "John Doe",
    "Age" : 100,
}
Run Code Online (Sandbox Code Playgroud)

如果你想在System.Json中使用烘焙:

var person = new Person()
var obj = JsonObject.Parse(json);

person.Name = obj["Name"].ToString();
person.Age = (int)obj["Age"];
Run Code Online (Sandbox Code Playgroud)

强烈建议使用ServiceStack.Text,它是一个高度优化的极快库,用于消费JSON,兼容MonoTouch和Mono for Android ......开箱即用!

您可以在此处查看使用ServiceStack消费JSON的API .