Search code examples
angularjsjsonasp.net-mvchttp-getjsonresult

JSON received as massive string in .data when sent to AgularJS from MVC


I get a JSON result from a Restful API and ensure the result is JSON in MVC Controller Method as follows:

public JsonResult GetApplications()
        {
            string appsRAW;
            HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create("http://apiurl.com/Api/Application/FullDetails");
            GETRequest.Method = "GET";
            GETRequest.Headers.Add("X-ApiKey", "key123");
            String username = "username";
            String password = "password";
            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
            GETRequest.Headers.Add("Authorization", "Basic " + encoded);
            HttpWebResponse response = GETRequest.GetResponse() as HttpWebResponse;
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                appsRAW=reader.ReadToEnd();            
            }            
            JsonResult applicationsJSON = Json(appsRAW, JsonRequestBehavior.AllowGet);

            return applicationsJSON;
        }

I then call this in Angular using:

$scope.applicationList;
    $http.get("/Home/GetApplications").then(function (result) {
        console.log(result);        
    });

However in the console output in .data all of the JSON from the api call is there but stored as a long string, store literally as...

data: "[{"Id":"a2ac8e01-3a5d-4110-8afe-2bde09a4f03b","Firstname":"John","Lastname":"Berry" ... etc. etc.

So I am unable to reference these values via result.data.Firstname for example, or ng-repeat through the applicant objects and display each field value.

Also not sure if important, when debugging and inspecting the C# Method, the .data appears with "\" before and after every field name and value, but when viewed in console in browser inspect they're gone.

I've succeeded in sending arrays to the angular from C# Method, and able to access via .data[0] .data[1] etc. this is first time trying to send actual JSON list of objects to angular from MVC.


Solution

  • You should be able to call JSON.parse on the data you're getting back to turn the string back into an object. Try this:

    JSON.parse(result.data)