【问题标题】:Monotouch: Deserialize JSON from MVC to MontouchMonotouch:将 JSON 从 MVC 反序列化为 Montouch
【发布时间】:2012-01-17 01:18:00
【问题描述】:

在我的测试 vb.net MVC web 应用程序中,我有这个 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

在 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);
}

还有这门课……

Public Class Person {
    Public string Name { get; set; }
    Public byte Age { get; set; }
}

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

谢谢! 魔力

【问题讨论】:

    标签: json model-view-controller xamarin.ios


    【解决方案1】:

    首先,我会使用 int 表示 Age。但假设 JSON 结构如下:

    {   
        "Name" : "John Doe",
        "Age" : 100,
    }
    

    如果您想使用 System.Json 中的烘焙内容:

    var person = new Person()
    var obj = JsonObject.Parse(json);
    
    person.Name = obj["Name"].ToString();
    person.Age = (int)obj["Age"];
    

    我会强烈推荐使用 ServiceStack.Text,它是一个高度优化的极快的 JSON 使用库,兼容 MonoTouch 和 Mono for Android...开箱即用!

    您可以查看使用 ServiceStack here 使用 JSON 的 API。

    【讨论】:

    • 谢谢!工作完美。是的,我今天查看了 ServiceStack,并试图找到一些 vb 示例来学习,但我做不到。所以我尝试设置它,但失败了。再次感谢!
    • 我在 MonoTouch 上使用 RestSharp。很像 ServiceStack。 RestSharp 也很好用。
    • RestSharp 一路!不仅仅是反序列化。它有助于让您的 Web 客户端保持清洁,消除大量重复的麻烦并处理 .NET 的 HttpWeb 类的许多缺陷。
    【解决方案2】:

    即使这个问题现在已经过时了,这也是我使用的解决方案。 借助 MonoTouch,您可以使用基于 DataContract 的 .net Json 序列化机制。

    [DataContract]
    Public Class Person {
        [DataMember]
        Public string Name { get; set; }
        [DataMember]
        Public byte Age { get; set; }
    }
    

    并使用 DataContractJsonSerializer(在 System.Runtime.Serialization.Json 中找到)

    Stream stream = httpRes.GetResponseStream ();
    DataContractJsonSerializer jsSerializer = new  DataContractJsonSerializer(typeof(Person));
    Person person = (Person)jsSerializer.ReadObject(stream);
    

    这样,代码符合 WCF 标准,并且可以在 ms.net 平台、mono 和 monotouch 上完美运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2023-04-10
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      相关资源
      最近更新 更多