Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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:
C#
[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:
XML
%<@ 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
Updated 9-Feb-11 5:00am
v2

1 solution

Use this webService ( your web service is also ok )
C#
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):
HTML
<!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
 
Share this answer
 
v2

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