How to convert datatable to json string using json.net WCF Rest Service
- Create WCF Service Project using C# 4.0/4.5
- Add a WCF service name it as IRestWCF
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
download Json.NET Add reference to Newtonsoft.JSon
<ServiceContract> _
Public Interface IRestWCF
<OperationContract> _
<WebGet(BodyStyle = WebMessageBodyStyle.WrappedResponse, ResponseFormat = WebMessageFormat.Json)> _
Dim GetDataTableJson() As Message
End Interface
Message class is the base class for all types of operations in WCF.
Public Class RestWCF
Implements IRestWCF
Public Function GetDataTableJson() As Message
Dim dt As DataTable = GetSalesData("json")
' Message message = WebOperationContext.Current.CreateJsonResponse<DataTable>(dt);
Dim strDatatable As String = Newtonsoft.Json.JsonConvert.SerializeObject(dt)
Return WebOperationContext.Current.CreateTextResponse(strDatatable,"application/json;charset=utf-8",System.Text.Encoding.UTF8)' Message.CreateMessage(MessageVersion.Default, "json datatable", message);
End Function
Private Function GetSalesData(ByVal format As String) As DataTable
Dim salesdata As DataTable = New DataTable("SalesPerson")
Try
Imports (SqlConnection conn = New SqlConnection("server=(local)\sqlexpress2012database=AdventureWorks2012uid=sapwd=password&"))
{
Imports (SqlDataAdapter adapter = New SqlDataAdapter("select * from (AdventureWorks2012).(Sales).(SalesPerson)", conn))
{
adapter.Fill(salesdata)
salesdata.AcceptChanges()
conn.Close()
}
}
Catch ex As SqlException
Throw ex
End Try
If format = "xml" Then
salesdata.RemotingFormat = SerializationFormat.Xml
End If
'else salesdata.RemotingFormat = SerializationFormat.Binary;
Return salesdata
End Function
End Class
Public Class RestWCF
Implements IRestWCF
Public Function GetDataTableJson() As Message
Dim dt As DataTable = GetSalesData("json")
' Message message = WebOperationContext.Current.CreateJsonResponse<DataTable>(dt);
Dim strDatatable As String = Newtonsoft.Json.JsonConvert.SerializeObject(dt)
Return WebOperationContext.Current.CreateTextResponse(strDatatable,"application/json;charset=utf-8",System.Text.Encoding.UTF8)' Message.CreateMessage(MessageVersion.Default, "json datatable", message);
End Function
Private Function GetSalesData(ByVal format As String) As DataTable
Dim salesdata As DataTable = New DataTable("SalesPerson")
Try
Imports (SqlConnection conn = New SqlConnection("server=(local)\sqlexpress2012database=AdventureWorks2012uid=sapwd=password&"))
{
Imports (SqlDataAdapter adapter = New SqlDataAdapter("select * from (AdventureWorks2012).(Sales).(SalesPerson)", conn))
{
adapter.Fill(salesdata)
salesdata.AcceptChanges()
conn.Close()
}
}
Catch ex As SqlException
Throw ex
End Try
If format = "xml" Then
salesdata.RemotingFormat = SerializationFormat.Xml
End If
'else salesdata.RemotingFormat = SerializationFormat.Binary;
Return salesdata
End Function
End Class
Web.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="restbeh">
<serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restendbeh">
<!--<soapProcessing processMessages="True"/>-->
<webHttp helpEnabled="True" faultExceptionEnabled="True"
defaultBodyStyle="Bare"/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="myrestbinding">
<security mode="None"></security>
<readerQuotas maxArrayLength="65536"/>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="WCFServicesREST.RestWCF" behaviorConfiguration="restbeh">
<endpoint contract="WCFServicesREST.IRestWCF" binding="webHttpBinding" bindingConfiguration="myrestbinding"
behaviorConfiguration="restendbeh"></endpoint>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="True"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" /> </system.webServer>
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCaching="true" enableCompression="true" />
</scripting>
</system.web.extensions>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="restbeh">
<serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restendbeh">
<!--<soapProcessing processMessages="True"/>-->
<webHttp helpEnabled="True" faultExceptionEnabled="True"
defaultBodyStyle="Bare"/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="myrestbinding">
<security mode="None"></security>
<readerQuotas maxArrayLength="65536"/>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="WCFServicesREST.RestWCF" behaviorConfiguration="restbeh">
<endpoint contract="WCFServicesREST.IRestWCF" binding="webHttpBinding" bindingConfiguration="myrestbinding"
behaviorConfiguration="restendbeh"></endpoint>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="True"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" /> </system.webServer>
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCaching="true" enableCompression="true" />
</scripting>
</system.web.extensions>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>