【发布时间】:2020-03-28 12:06:22
【问题描述】:
我想反序列化一个 json 请求,但它在 Web API 中不起作用。我的代码在下面用于反序列化。你能告诉我我做错了什么吗?
[HttpPost]
public HttpResponseMessage AddOrder(string username , string password, JObject jsonResult)
{
try
{
AuthRepository _auth = new AuthRepository();
OrderDTO.RootObject O = new OrderDTO.RootObject();
O = JsonConvert.DeserializeObject<OrderDTO.RootObject>(jsonResult.ToString());
}
catch (Exception ex)
{
return Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex);
}
}
这是我们的方法将接收到的 JSON:
{
"token": "D8xJD2CI6PrkB3q5gnlT",
"shipment": {
"hawb": "0800780108",
"service_level": "CURBSIDE",
"status": "NEW",
"description": "bundle of things",
"service_level_code": "CB",
"delivery_date": "8/22/2019 5:01:00 PM",
"delivery2_date": "8/22/2019 12:00:00 AM",
"origin": {
"name": "ESTES EXPRESS BOSTON-080",
"nbr": "0800780108",
"phone": "508-513-0120",
"email": "",
"address1": "215 BODWELL ST",
"city": "AVON",
"state": "MA",
"zip_postal_code": "02322",
"country": "US"
},
"dest": {
"name": "JOSEPH VINOGRAD",
"nbr": "",
"phone": "",
"email": "",
"address1": "14 CORTLAND DR",
"city": "Sharon",
"state": "MA",
"zip_postal_code": "02067",
"country": "US"
},
"piece_count": "2",
"dangerous_goods": "0",
"weight": 190
}
}
类代码
public class OrderDTO
{
public class Origin
{
public string name { get; set; }
public string nbr { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string address1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip_postal_code { get; set; }
public string country { get; set; }
}
public class Dest
{
public string name { get; set; }
public string nbr { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string address1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip_postal_code { get; set; }
public string country { get; set; }
}
public class Shipment
{
public string hawb { get; set; }
public string service_level { get; set; }
public string status { get; set; }
public string description { get; set; }
public string service_level_code { get; set; }
public string delivery_date { get; set; }
public string delivery2_date { get; set; }
public Origin origin { get; set; }
public Dest dest { get; set; }
public string piece_count { get; set; }
public string dangerous_goods { get; set; }
public double weight { get; set; }
}
public class RootObject
{
public string token { get; set; }
public Shipment shipment { get; set; }
}
}
【问题讨论】:
-
“它不工作”。什么不工作?您收到错误消息吗?如果是这样,那是什么信息?它发生在何时何地?
-
不确定这是否是您遇到的问题,请尝试
AddOrder(string username , string password, [FromBody] RootObject jsonResult)
标签: c# asp.net-web-api c#-4.0 json-deserialization