【问题标题】:API accepts an object, passing an object as json, Only taking top layer of the objectAPI接受一个对象,将一个对象作为json传递,只取对象的顶层
【发布时间】:2014-05-13 14:55:35
【问题描述】:

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

订单类别:

 [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 都为空。

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

 [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);

【问题讨论】:

  • ProductAddress 类是否也标记为 [Serializable]
  • 您使用的是哪个 json 序列化器/反序列化器(两边是否相同)?
  • 请显示引用的类,以便回答这个问题。
  • 好的更新了我的问题,@EkoostikMartin 两个类也是可序列化的 :(
  • 这是从您的客户端发送到 webapi 的 json,但是您查看过请求标头吗?它实际上是否正确发送了所有这些内容?

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


【解决方案1】:

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

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

【讨论】:

  • 顺便说一句,删除该属性可能听起来不直观,但意识到它被添加到框架的原因是有道理的。
猜你喜欢
  • 2023-03-24
  • 2015-09-15
  • 2015-03-13
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多