Troubleshooting JSON Deserialization
I've reviewed recent posts regarding deserialization:
- WCF not deserializing JSON input
- Generic WCF JSON Deserialization
- Need help with: "The remote server returned an unexpected response: (400) Bad Request."
but using the troubleshooting methods provided, I was unable to solve my current issue. It looks like I'm not the only one having trouble finding a proven method either, so I hope that a solution will help out quite a few individuals. I've even searched Safari Books Online and the general impression I get is that JSON support is for Silverlight only.
At the moment I'm not considering moving to JSON.net unless it is the only way to accomplish my goal: posting a JSON object to a .NET WCF web service and updating the appropriate record in my database. I've followed Service Monitor traces, netmon traces, etc., and they all show that my service endpoint doesn't appear to be passing the JSON input to the method I've declared for parsing out individual JSON properties.
My Operation Contract:
//Update Ticket
[OperationContract]
[WebInvoke(Method = "PUT",
UriTemplate = "UpdateTicket",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
TimeTicket UpdateTicket(TimeTicket t);
My data contract:
[Serializable]
[DataContract]
public class TimeTicket
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Project { get; set; }
[DataMember]
public int Hours { get; set; }
[DataMember]
public DateTime Date { get; set; }
}
A partial for the method that handles the JSON data. It fails at the line "where x.ID == t.ID" because t is a null object:
public TimeTicket UpdateTicket(TimeTicket t)
{
MWAEntities db = new MWAEntities();
var tick = (from x in db.TEST_TimeTicket
where x.ID == t.ID
select new TimeTicket
{
ID = x.ID,
Project = x.project,
Hours = x.hours,
Date = x.date
}).FirstOrDefault();
During execution, I'm using curl (on Mac OS X) to send JSON data as follows:
curl -X PUT http://mywebserver:8000/UpdateTicket -d '{"ID":1,"Project":"Project A-edit2","Hours":32,"Date":"\/Date(1301630400000-0400)\/"}' -H "Content-Type:application/json" -v
Verbose output:
* About to connect() to mywebserver port 8000 (#0)
* Trying 192.168.210.218... connected
* Connected to mywebserver (192.16开发者_开发百科8.210.218) port 8000 (#0)
> PUT /UpdateTicket HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3
> Host: mywebserver:8000
> Accept: */*
> Content-Type:application/json
> Content-Length: 85
Netmon traces show that the server receives the JSON I'm passing it.
Is there a way to determine what's happening to my JSON and best practices for handling the data? Thanks for the education!
Chad_C, Hi.
I think your JSON payload should be:
'{"t":{"ID":1,"Project":"Project A-edit2","Hours":32,"Date":"\/Date(1301630400000-0400)\/"}}'
t being your TimeTicket (UpdateTicket(TimeTicket t))
精彩评论