API
Version 7.x > API > Web service return as JSON View modes: 
User avatar
Certified Developer v7
Certified  Developer v7
yoek - 7/23/2013 2:45:09 AM
   
Web service return as JSON
Hi Guys,

Is there any special settings in Kentico to render web service as JSON?

In my code which is in WebService.cs, I already declare ScriptMethod to response as JSON, but still header response as a XML.

I pasted my code as bellow

using System;
using System.Collections.Generic;
using System.Web;
using System.Collections;
using System.Data;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using CMS.CMSHelper;
using CMS.GlobalHelper;

/// <summary>
/// Empty web service template.
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
/// <summary>
/// Constructor.
/// </summary>
public WebService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}


/// <summary>
/// Returns the data from DB.
/// </summary>
/// <param name="parameter">String parameter for sql command</param>
[WebMethod]
public DataSet GetDataSet(string parameter)
{
// INSERT YOUR WEB SERVICE CODE AND RETURN THE RESULTING DATASET

return null;
}


/// <summary>
/// The web service method to be called by AJAXControlToolkit. The signature of this method must match this method.
/// Note that you can replace "GetCompletionList" with a name of your choice, but the return type and parameter name and type must exactly match, including case.
/// </summary>
/// <param name="prefixText">Prefix to be searched</param>
/// <param name="count">Number of suggestions to be retrieved from the web service</param>
/// <returns>Array of suggestions</returns>
[WebMethod(MessageName = "GetCompletionList")]
[ScriptMethod]
public string[] GetCompletionList(string prefixText, int count)
{
// INSERT YOUR WEB SERVICE CODE AND RETURN THE RESULTING STRING ARRAY

return null;
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetTreeNodeNames(string pathParameter)
{
if (string.IsNullOrEmpty(pathParameter))
throw new ArgumentException("No PathParameter specified");

int cacheMins = 30;
string cacheKeyName = "GetTreeNodeNames";
DataSet ds = null;
var treeNodes = new List<string>();

using (var cs = new CachedSection<DataSet>(ref ds, cacheMins, true, null, cacheKeyName, pathParameter))
{
if (cs.LoadData)
{
// Get from database
ds = TreeHelper.SelectNodes(pathParameter, false, "CMS.MenuItem");
CacheHelper.GetCacheDependency("touchthis".ToLower());
//cs.CacheDependency = ...
cs.Data = ds;
}
}

if (ds != null)
{
if (ds.Tables.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
treeNodes.Add(dr["NodeName"].ToString());
}
}
var jsr = new JavaScriptSerializer();
string output = jsr.Serialize(treeNodes);

return output;


}
}

User avatar
Member
Member
Swainy - 7/23/2013 5:58:39 AM
   
RE:Web service return as JSON
Hi,

Instead of returning a string, why not return an action result and then you can use a proper JSonResult object and pass in your data to the data property of it?

Then you get your type safed Json objects rather than a big string returned, which makes it easier when dealing with JQuery on the other side.

Thanks,

Matt

User avatar
Member
Member
eagleag - 9/3/2013 5:39:11 PM
   
RE:Web service return as JSON
Was this solved? any chance to see the code that works?

many thanks :)

User avatar
Member
Member
Swainy - 9/4/2013 4:11:11 AM
   
RE:Web service return as JSON
Hi Eagle,

What is it your trying to do?

I could probably give you some code that works (or thereabouts).

Thanks,

Matt

User avatar
Member
Member
jwynveen - 11/1/2013 4:55:26 PM
   
RE:Web service return as JSON
I just tried creating a controller that returns a list of documents as json, but when accessing it I get the following error:
Type 'System.Collections.Hashtable' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.

This is my code:
public class DataController : Controller
{
public ActionResult Files()
{
var documents = TreeHelper.GetDocuments(CMSContext.CurrentSiteName, "/Files/%", CMSContext.PreferredCultureCode, true, "CMS.File", null, "", -1, true, 0);
return Json(documents.ToList());
}
}

What do I need to the TreeNodeDataSet in order to be able to serialize it as a JsonResult?

User avatar
Kentico Support
Kentico Support
kentico_zdenekc - 12/9/2013 4:44:49 PM
   
RE:Web service return as JSON
Hi,

You need to serialize the data first. In our REST service, we use
public static string ToJSON(this DataSet ds, bool includeName)

from CMS.GlobalHelper.Extensions namespace

This method exports DataSet to JSON string, ds is DataSet to export and includeName indicates, if name of the dataset and names of the tables should be included in the result.
Hope this will help.

Regards,
Zdenek