Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# JSON WebService
I am trying to get a basic json web service to return data and keep running into the same problem. The json object returned does not seem to contain any data.
 
Here is my web service:
        [WebMethod(Description = "This is a test JSON service", EnableSession = false)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string testJSON(string a, string b, string c, string d, string e, string f)
        {
            string temp = "Data " + a + " " + b + " " + c + " " + d + " " + e + " " + f;
 
            //yourobject is your actula object (may be collection) you want to serialize to json
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(temp.GetType());
            //create a memory stream
            MemoryStream ms = new MemoryStream();
            //serialize the object to memory stream
            serializer.WriteObject(ms, temp);
            //convert the serizlized object to string
            string jsonString = Encoding.Default.GetString(ms.ToArray());
            //close the memory stream
            ms.Close();
            return jsonString;
 
            //return temp;
        }
 
The return jsonString is in the format "\"Data a s d f g h\"" when a s d f and g are entered for the parameters. This works fine in the .net testing window, but only returns xml, not json (it is my understanding that the .net test only ever returns xml. Is that true? Can you see json from the test page?)
 
Here is my page where I try to call this service:
%<@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script src="jquery-1.3.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        function getProducts(a,b,c,d,e,f) {
            $('#divResults').hide();
            $('#divLoading').show();
            try {
                    $.ajax({
                        type: "POST",
                        url: /Service1.asmx/testJSON",
                        data: "{'a' : 'a', 'b' : 's', 'c' : 'd', 'd' : 'f', 'e' : 'g', 'f' : 'h'}",
                        contentType: "application/json; charset=utf-8",
                        success: ajaxCallSucceed,
                        dataType: "json",
                        failure: ajaxCallFailed
                    });
                    //JsonWebServiceWithJQuery/jsonwebservice.asmx?op=GetProducts
            }
            catch (e) {
                alert('failed to call web service. Error: ' + e);
                $('#divLoading').hide();
            }
        }
        function ajaxCallSucceed(response) {
            $('#divLoading').hide();
            alert("Succeed");
//            var products = eval('(' + response.d + ')');
            alert(response.responseText);
            alert(response.toString());
       }
        function ajaxCallFailed(error) {
            $('#divLoading').hide();
            alert('error: ' + error);
            $('#divResults').hide();
        }
    </script>
alert(response.responseText) is returning undefined
alert(response.toString()) is returning [object Object]
 
Any help would be very very appreciated. I have been banging my head against the wall on this one for days now and am making no progress.
 
Thanks!
Posted 8-Feb-11 12:40pm
Edited 9-Feb-11 6:00am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Use this webService ( your web service is also ok )
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
using MvcApplication1.Models;
using System.Web.Script.Services;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
 
namespace MvcApplication1
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, 
    // using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
 
        [WebMethod]
        public string testJSON(string a, string b, string c, string d, string e, string f)
        {
            string temp = "Data " + a + " " + b + " " + c + " " + d + " " + e + " " + f;
 
            //yourobject is your actula object (may be collection) you want to serialize to json
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(temp.GetType());
            //create a memory stream
            MemoryStream ms = new MemoryStream();
            //serialize the object to memory stream
            serializer.WriteObject(ms, temp);
            //convert the serizlized object to string
            string jsonString = Encoding.Default.GetString(ms.ToArray());
            //close the memory stream
            ms.Close();
            return jsonString;
        }
    }
}
This is the page where it try to call the service (I made some changes to getProducts function):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function getProducts(a, b, c, d, e, f) {
            $('#divResults').hide();
            $('#divLoading').show();
            try {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/Service1.asmx/testJSON",
                    data: "{'a' : '1', 'b' : '2', 'c' : '3', 'd' : '4', 'e' : '5', 'f' : '6'}",
                    dataType: "json",
                    success: function (data) {
                        $('#divLoading').hide();
                        alert("Succeed");
                        $('#divResults').show();
                        $('#divResults').html(data.d);
                    },
                    error: function (result) {
                        $('#divLoading').hide();
                        alert('error: ' + error);
                        $('#divResults').hide();
                    }
                });
            }
            catch (e) {
                alert('failed to call web service. Error: ' + e);
                $('#divLoading').hide();
            }
        }
    </script>
</head>
<body>
    <div id="divLoading" style="display:none">
        Loading
    </div>
    <div id="divResults" style="display:none">
    </div>
    <button onclick="getProducts()">getProducts</button>
</body>
</html>
After you click on getProducts button "Succeed" alert will show and then divResults contains:
"Data 1 2 3 4 5 6"
Hope it helps
  Permalink  
v2

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

  Print Answers RSS
0 OriginalGriff 428
1 Maciej Los 249
2 BillWoodruff 199
3 /\jmot 180
4 Suraj Sahoo | Coding Passion 150
0 OriginalGriff 8,484
1 Sergey Alexandrovich Kryukov 7,407
2 DamithSL 5,639
3 Maciej Los 5,159
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web02 | 2.8.1411023.1 | Last Updated 25 Apr 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100