0

I have written WebApi filter to detect concurrency issues. In action OnActionExecuted I set response content like below: enter image description here

actionExecutedContext.Response.Content = new System.Net.Http.StringContent( "'{ \"hasValidationErrors\": true, \"validationErrors\": " + System.Web.Helpers.Json.Encode( validationErrors ) + ", \"concurrencyIssue\": true }'", System.Text.Encoding.UTF8, "application/string" );

When I receive it and write to console it looks like on below printscreen

Then, When I try to do:

JSON.parse(response.data)

I get error:

SyntaxError: Unexpected token ' in JSON at position 0

but when I do

JSON.parse( response.data.substring(1, response.data.length - 1) )

it works as expected, mean convert string to json data.

So my question is, why I have to truncate response.data? I gues that, as can be seen in first line on printscreen, there are additional quotemarks. But how can I create my server response to not put them there? And why, when I log response.data ( thrid line on printscreen ), there are only apostrophe, but no quotemarks?

0

1 Answer 1

1

This means your JSON is not valid. Try to create a model class for your response. Then Parse.

Example :

public class Response
{
   public bool hasValidationErrors;
   //public YourType validationErrors;
   public bool concurrencyIssue;         
 }
 var obj = new Response();
 obj.hasValidationErrors = true;
 obj.concurrencyIssue = true;         
 var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
 //Set Your Response

Hope this helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot - Newtonsoft.Json.JsonConvert.SerializeObject do its job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.