【发布时间】: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);
【问题讨论】:
-
Product和Address类是否也标记为[Serializable]? -
您使用的是哪个 json 序列化器/反序列化器(两边是否相同)?
-
请显示引用的类,以便回答这个问题。
-
好的更新了我的问题,@EkoostikMartin 两个类也是可序列化的 :(
-
这是从您的客户端发送到 webapi 的 json,但是您查看过请求标头吗?它实际上是否正确发送了所有这些内容?
标签: c# .net rest .net-3.5 asp.net-web-api