views:

983

answers:

2

By default WCF service wrap JSON response in "d" wrapper and there I found a problem with parsing it.

If I parse with JsonConvert.DeserializeObject(response) where response is

"{\"d\":\"{\"a0b70d2f-7fe4-4aa2-b600-066201eab82d\":\"Thelma\",\"d56d4d4f-6029-40df-a23b-de27617a1e43\":\"Louise\"}\"}"

I gor an Error:

After parsing a value an unexpected character was encoutered: a. Line 1, position 9.

If I change response into

"{\"a0b70d2f-7fe4-4aa2-b600-066201eab82d\":\"Thelma\",\"d56d4d4f-6029-40df-a23b-de27617a1e43\":\"Louise\"}"

I got it working.

So how to parse this "d" wrapped JSON responses from WCF services? Is there any better way to parse JSON?

A: 

Looks like you're using the enableWebScript behavior on your webHttpBinding. You should probably be using the webHttp behavior instead- this gives you "clean" JSON instead of the ASP.NET AJAX client JSON.

nitzmahone
I tried to change this but then I got an error:Operation 'Save' of contract 'Organization' specifies multiple request body parameters to be serialized without any wrapper elements. At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped.Where my Save methos looks like:[OperationContract]bool Save(string orgGuid, string orgName, string orgCode, string orgAddress, int orgStatus)Otherwise this "d" wrapper is OK, but why it produce error on parsing?
AnzeR
A: 

Now I got rid of "d" wrapper with Regex.Replace and fix JSON response with proper structure

{\"Guid\":\"a0b70d2f-7fe4-4aa2-b600-066201eab82d\",\"Name\":\"Thelma\"}
{\"Guid\":\"d56d4d4f-6029-40df-a23b-de27617a1e43\",\"Name\":\"Lousie\"}\"}

I also make a class with Guid and Name, defined as string in it.

Then try to deserialize it with

List<myStruct> o = JsonConvert.DeserializeObject<List<myStruct>>(response);

But i get an error

Expected a JsonObjectContract or JsonDictionaryContract for type 'System.Collections.Generic.List`1[mynamespace.myStruct]', got 'Newtonsoft.Json.Serialization.JsonArrayContract'.

Where is the trick?

AnzeR
I'm checking examples on http://james.newtonking.com/projects/json-net.aspx. OK, this all is working nice if you have only one record in the JSON string, but if you have more of then...
AnzeR