2017-02-14 48 views
2

我在使用HttpResponseMessage獲取多個Json對象時遇到問題 如何在沒有將字符串打包爲Json的情況下實現這個功能?如何通過Web API將多個json對象作爲HttpResponseMessage返回?

這是我迄今爲止嘗試過的代碼......

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); 
} 

它工作正常,但它本身附加「\ n \ r」。如何解決這個問題或者其他替代方案?由上述代碼

{"jsonString":["{\r\n \"resourceType\": \"Patient\",\r\n \"entry\": []\r\n}","ABC"]} 
+0

又有連載回JSON您的匿名對象結果之前,反序列化傳入jsonString回對象你用Newtonsoft JsonConvert.SerializeObject(YOUROBJECT,Formatting.None)嘗試過; –

+0

是的..它產生相同的結果 –

+0

它可以嗎?... –

回答

2

這被返回的響應彷彿你一個序列化的對象的兩倍。

如果目的是爲了返回合適的對象,那麼你需要在創建最終獲得在HTTP meddage響應

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); 
} 
相關問題