Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to jSON serialize a .NET DataTable in WCF?

When I configure WCF to use jSON serialization, and include a DataTable in one of my DataContracts, it serializes the DataTable to XML before serializing the entire DataContract to jSON. I want the DataTable to be serialized as jSON, not XML.

My questions are:

  1. Why does it serialize the DataTable to XML first?
  2. How can I get it to serialize to jSON instead?
like image 641
rhyno Avatar asked Jul 29 '13 15:07

rhyno


People also ask

How do you serialize an object in WCF?

This code constructs an instance of the DataContractSerializer that can be used only to serialize or deserialize instances of the Person class. DataContractSerializer dcs = new DataContractSerializer(typeof(Person)); // This can now be used to serialize/deserialize Person but not PurchaseOrder.

Is DataTable serializable C#?

A DataTable can't be used with Web service methods and doesn't provide a direct way to serialize its contents.

What is the name of the method belongs to class DataContractJsonSerializer which is used to serialize the JSON data?

To deserialize an instance of type Person from JSON Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.


1 Answers

  1. DataTable is a pure .NET construct which cannot be (easily) represented in a lossless manner by JSON. DataTables contain lots of additional information which JSON cannot store: Primary keys, autoincs, allow nulls, caption, data type, indexes, etc. Serialization to XML/Binary are the only ways a DataTable can be serialized natively by .NET. This XML serialized DataTable is then serialized to JSON.

  2. Use JSON.NET or FastJSON to convert a DataTable to a plain, clean JSON-compatible version of the DataTable, which can be consumed by any JSON client, not just .NET WCF clients. You will lose all DataTable custom properties mentioned in (1) above and only get the field name/value JSON pair. Storage in this fashion is inefficient due to the duplication of field names in every row.

Don't use DataTable in your DataContract. If you want the benefits of a DataTable and your clients are always going to be .NET, serialize the DataTable to a byte array via Binary Serialization and then optionally compress the resultant serialized byte stream. Expose a byte array in your DataContract. This will give you an efficient, fully lossless version of the DataTable on the client-side (after decompression and binary deserialization), not a watered-down JSON version of a DataTable (as offered by (2))...

like image 105
Keith Blows Avatar answered Sep 19 '22 18:09

Keith Blows