user393014
user393014

Reputation: 475

json response coming with newline character asp.net mvc

Hi I am using an asp.net MVC controller to query a third party REST API.

I am getting a response but it has newline characters in the response.

{\n \"from\": 1,\n \"to\": 10,\n \"total\": 500570,\n \"currentPage\": 1,\n....

I am returning this to a view and the view is not able to read it because of \n.

I am using the following code to make the call and get the result

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

In the view side following script

<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>

What am I doing wrong here?

Upvotes: 1

Views: 3697

Answers (1)

bill_Stack
bill_Stack

Reputation: 21

If you want to remove all the \n Characters you can remove the NewLines in the Controller before send it to view:

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

If you want to keep the NewLine Characters you must Escape them in Javascript before you parse 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
    });
});

Upvotes: 2

Related Questions