3

I'm having a problem getting multiple Json objects using HttpResponseMessage. How can this be acheived without wrapping the string as Json?

This is the code that I have tried so far...

private HttpResponseMessage SetToJson(string jsonString)        
{     
  string str = "ABC";

  HttpRequestMessage Request = new HttpRequestMessage();
  Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
  Request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

  return Request.CreateResponse(HttpStatusCode.OK, new { jsonString, str }, JsonMediaTypeFormatter.DefaultMediaType);
}

It works fine, but it appends \r\n" by itself. How can this be fixed? Is there any other alternative?

This is the returned response by the above code

{"jsonString":["{\r\n  \"resourceType\": \"Patient\",\r\n  \"entry\": []\r\n}","ABC"]}
5
  • have you tried with Newtonsoft JsonConvert.SerializeObject(YOUROBJECT, Formatting.None); Commented Feb 14, 2017 at 10:10
  • yes .. it produces same result Commented Feb 14, 2017 at 10:27
  • is it ok so?... Commented Feb 14, 2017 at 10:30
  • no... i still have same problem Commented Feb 14, 2017 at 12:02
  • 1
    What are you ultimately trying to accomplish? As it stands, the json text that you are returning is not really correctly formatted, ignoring the \r\n. WebApi is attempting to serialize the json string that you have in an array with your str variable. Are you trying to add a property to the json string? Commented Feb 14, 2017 at 13:00

1 Answer 1

3

Seems as though you a serializing an object twice.

If the intention was to return proper objects then you need to deserialize the incoming jsonString back to an object before creating your anonymous object result which eventually get serialized back to json again in the http meddage response

private HttpResponseMessage SetToJson(string jsonString) { 
    string str = "ABC";

    var Request = new HttpRequestMessage();
    Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
    Request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

    var obj = JsonConvert.DeserializeObject(jsonString);

    return Request.CreateResponse(HttpStatusCode.OK, new { obj, str }, JsonMediaTypeFormatter.DefaultMediaType);
}
Sign up to request clarification or add additional context in comments.

Comments

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.