Here's the scenario: C# middle tier webservice has the data sent from SQL Server in a System.Data.DataTable object. There are dozens of columns in the DataTable's columns collection. The browser client only needs to see about six of them. The stored proc on the server is general purpose, not designed for this specific task. Assume we have to use it, rather than writing a new SP.
Is there a simple way, perhaps using generics, to extract the desired subset of columns from that DataTable into a List or a Collection, and then convert the resulting list or collection to JSON using JSON.NET?
Is it possible to create a skeletal C# class definition foo
with the relevant field names (and datatypes) and then match on those field names "automagically" and thereby generate a List<foo>
from the DataTable's rows collection?
Ideally, during the JSON conversion, any SQL Server datetime values (e.g. 2014-06-24T18:45:00
) would be converted to a value that would make it easy to instantiate a javascript Date in the client without having to do string manipulation of the date representation.
Full working Console App code pasted below. But the 2 main methods you need are as follows.
For this code to work, you will have to do the following in your Project.
JSON.Net
Nuget Package to the Project.Add a reference to
System.Web.Extensions
(if you get a compile error in the line whereSystem.Web.Script.Serialization.JavaScriptSerializer
is being referenced in theGetJson
method.Fully working Console App code.
Create a new console App, and replace everything in the
Program.cs
with this code. Also add JSON.Net to the Console App Project and add the references toSystem.Web.Extensions
.Explanation of Code:
Notice I have 2 classes,
Patient
andPatientDrug
. I wrote helper methods to return data tables for both classes, that have additional columns. Then the following 2 lines get the JSON for the class representation forPatient
andPatientDrug
respectively, while ignoring the additional data columns in DataTable that don't match names.Output in Console Windows (the json strings)