2011-02-07 58 views
1

嗨 我正在使用一個asp.net MVC控制器來查詢第三方REST API。JSON響應與換行符字符聊天室asp.net mvc

我得到一個響應,但它在響應中有換行符。從\「:1,\ n \」到\「:10,\ n \」全部\「:500570,\ n \」currentPage \「:1,\ n ... 。

我將此視圖返回到視圖,並且由於\ n視圖無法讀取它。

我使用下面的代碼來撥打電話,並得到結果

public JsonResult Items(string search) 
    { 

     var client = new WebClient(); 
     string url = "http://xxxxxxxxxxxxxxx/v1/products?apiKey=xxxxxxxxxx&format=json"; 


     JsonResult json = Json(client.DownloadString(url), "text/x-json",Encoding.UTF8, JsonRequestBehavior.AllowGet); 


     return json; 
    } 

在觀察側下面的腳本

<script type="text/javascript"> 

    $(function() { 
     $('#searchlink').click(function() { 
      $.getJSON("Item/Items", $("#search").val(), getitems); 

     }); 
    }); 

    function getitems(responses) { 
     alert(responses); 

     $.each(responses, function (index, response) { 
       // do stuff 
     }); 
    } 

</script> 

我在做什麼錯在這裏?

+0

您是否驗證過API的響應不包括換行符? – 2011-02-08 01:49:25

回答

2

如果你想刪除所有\ n個字符,你可以刪除控制器中的換行符之前發送到視圖:

string result=client.DownloadString(url); 
result=result.Replace("\r", "").Replace("\n", "\n"); 

如果你想保留換行符,你必須在逃離他們在Javascript 您解析Json:

$.get("Item/Items", $("#search").val(), getitems(data) { 
    //Escape \r,\n 
    data=data.replace(/\n/g, "\\n").replace(/\r/g, "\\r"); 
    //and parse Json 
    responses=jQuery.parseJSON(data); 
    alert(responses); 

    $.each(responses, function (index, response) { 
      // do stuff 
    }); 
});