I have a service that attempting to serialize a list into JSON (using JSON.NET) and return as a string. That’s all well and good, but my JSON is coming back wrapped and I can’t figure out why.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[{"DoNotSolicitID":5,"FirstName":"test","LastName":"mcTest","Address1":"11 Elm St","Address2":null,"City":"testville","State":null,"Zip":null,"Zip4":null,"Email":"test@mcTest.com","Phone":null,"BusinessName":null,"PartnerID":"3","Origination":"RDI"},{"DoNotSolicitID":6,"FirstName":"test","LastName":"mcTest","Address1":"11 Elm St","Address2":null,"City":"testville","State":null,"Zip":null,"Zip4":null,"Email":"test@mcTest.com","Phone":null,"BusinessName":null,"PartnerID":"3","Origination":"RDI"}]</string>
The code making the call is:
return JsonConvert.SerializeObject(Lookup(guid, criteria), Formatting.None);
private IList<DNSContract> Lookup(string guid, SearchCriteria criteria)
{
apiAuthentication = new APIKeyAuthentication();
if (!apiAuthentication.IsValidAPIKey(guid))
throw new WebFaultException<string>("Invalid Key", HttpStatusCode.Forbidden);
var searchObj = ToSearchObject(criteria);
SetContext();
return Svc.SelectWithCriteria(searchObj).Data;
}
UPDATE: This is a WCF service and in the browser, and fiddler I get the same XML tags. Also, making the call from jQuery/ajax blows up, presumably because it’s getting the tags as well, not the JSON.
UPDATE 2: the SetContext() call will set the ContentType based on the desired type. In this case I’m simply doing the following for JSON in the base class for the REST services:
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.ContentType = "application/json";
response.StatusCode = HttpStatusCode.OK;
So I’m setting the ContentType in teh rsponse and returning a string as a simple output in the service method. This is the interface I’m implementing:
[OperationContract]
[WebGet(UriTemplate = "/{guid}/search/json?fname={firstname}&lname={lastname}&phone={phone}&email={email}&add1={address1}&add2={address2}&city={city}&state={state}&zip5={zip5}")]
string LookupRecord(string guid, string firstname, string lastname, string phone, string email, string address1, string address2, string city, string state, string zip5);
Perhaps something in the WebGet that I need to explicitly format to be JSON?
My problem was that I was not setting the context’s OutgoingResponse.Format to JSON. The context code for a valid JSON response in my situation is
Oddly enough, setting the attributes on the web method didn’t do anything, I had to set the context explicitly. Since I need to handle XML and JSON responses, this seems the best approach I’ve found.