Click here to Skip to main content
15,562,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I have made one Rest service in WCF (demo) , which gives me output as : {"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}}

Now i have created one website in asp.net in which i am calling this rest service through AJAX JSON...

my code is as below:
<script type="text/javascript">
       $(document).ready(function () {
           //            $.getJSON("http://localhost/SampleService/Service1.svc/getJson?callback=?", null, function (data) {
           //                alert(data.Name);
           //            });

           var endpointAddress = "http://localhost/SampleService/Service1.svc";
           var url = endpointAddress + "/GetJson";
           $.ajax({
               type: 'GET',
               url: url,
               dataType: 'jsonp',
               contentType: 'application/json',
               data: "{}",
               success: function (result) {
                   //alert(JSON.stringify(result));
                   alert(result.length);
               },
               error:function(jqXHR)
               {
                   alert(jqXHR.status);
               }
           });

       });
   </script>

You could see that i have accessed service through both AJAX and getJSON methods..

now when i am making a alert of data , it shows me output as undefined..
i have tried :
alert(result.d.length) , alert(result.d.GetEmployeeJSONResult)... but always shows me as undefined..in both methods..

Please help me out how to handle this..


Thanking you in advance.

Krunal
Posted

1 solution

Krunal,

Try this :

var result = data.GetEmployeeJSONResult;
var id = result.Id;
var name = result.Name;
var salary = result.Salary;

Or if you want to directly alert try this : alert(data.GetEmployeeJSONResult.Id);

You need to understand how JSON works. Comparing the JSON data with XML for simplification ,here 'GetEmployeeJSONResult' it the main object (parent) , so you have to traverse to it first. And then access the child node values.

P.S. : XML and JSON are totally different .

Let me know if this solves your problem.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900