API接受一个对象,将对象作为json传递,只接受对象的顶层

时间:2014-05-13 14:55:35

标签: c# .net rest .net-3.5 asp.net-web-api

我有一个接受Order类的WebAPI。我创建了Order类并将其序列化,将其转换为字符串,然后将其传递给我的web api。数据就在那里,但是当我在API端反序列化时(仅用于测试,因为我得到一个空引用错误),我的大多数对象都返回null(除了对象的顶层之外)< / p>

订单类:

 [Serializable]
    public class Order
    {
        public Address Address { get; set; }
        public DateTime OrdereDate { get; set; }
        public DateTime DeliveryDate { get; set; }
        public IList<Product> ProductList { get; set; }
    }

我称之为api方法的原始Json字符串就是这样

{
    "Address" : {
        "AddressLine1" : "line1",
        "AddressLine2" : "",
        "City" : "Test",
        "Province" : "ON",
        "PostalCode" : "90210",
        "Country" : "US",
        "Email" : "test@gmail.com",
        "Phone" : "234567876"
    },
"OrdereDate" : "\/Date(1400198100000)\/",
    "DeliveryDate" : "\/Date(1400753100000)\/",
"ProductList" : [{
            "ProductCode" : "GT",
            "Name" : null,
            "Description" : null,

        }, {
            "ProductCode" : "CI",
            "Name" : null,
            "Description" : null,
        }
    }

这是传递给API的内容,但如果我将对象反序列化为Order对象,则Address和ProductList都为null。

编辑:其他类也被标记为序列化

 [Serializable]
    public class Product
    {
        public string ProductCode { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
  [Serializable]
    public class Address
    {
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public string Province { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

我的序列化/ API调用

WebClient client = new WebClient();
                JavaScriptSerializer js = new JavaScriptSerializer();
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                string serialisedData = js.Serialize(order);

                var response = client.UploadString("mysite.com/Order/NewOrder", serialisedData);

1 个答案:

答案 0 :(得分:0)

这是一个快速赃物:从类中删除[Serializable]属性,然后重试。 Web API与WCF的工作方式不同,WCF是为其设计的。这通常足以使事情正常运作。

注意:如果您需要进行更深入的JSON映射,那么Web API并不像其他一些JSON库那样成熟。幸运的是,您可以在其上放置其他JSON序列化程序并包含JSON.NET,因此您可以使用其方法(和属性)进行序列化,而不是开箱即用。如果您需要更多JSON序列化/反序列化支持,那么这就是我的目标。