什么是最好的方式,JSON序列化WCF一个.NET数据表? [英] What's the best way to jSON serialize a .NET DataTable in WCF?

查看:209
本文介绍了什么是最好的方式,JSON序列化WCF一个.NET数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我WCF配置使用JSON序列化,包括在我的DataContracts一个数据表,它系列化数据表到XML序列化整个DataContract为JSON之前。我想在数据表被序列化为JSON,而不是XML。

我的问题是:

  1. 为什么会先序列化数据表到XML?
  2. 我怎样才能得到它的序列化到JSON呢?
解决方案
  1. 数据表是一个纯.NET结构,它不能由JSON psented以无损的方式(容易)重新$ P $。数据表含有大量的这些JSON不能存储更多的信息:主键,autoincs,允许为空,说明,数据类型,索引等序列化到XML /二进制是一个DataTable可以通过本地.NET序列化的唯一途径。这种XML序列化的DataTable被序列化到JSON。

  2. 使用 JSON.NET 或的 FASTJSON 到DataTable转换为一个普通的数据表,它可以由任何JSON的客户,而不只是.NET WCF被消耗干净JSON兼容的版本客户端。您将失去在(1)中提及的所有数据表自定义属性上面,只得到字段名/值对的JSON。存储以这种方式是低效的,由于每一行中的字段名重复。

不要在您的DataContract使用的数据表。如果你想要一个DataTable和您的客户带来的好处总是会被.NET中,序列化的DataTable通过二进制序列化的字节数组,然后任选COM preSS产生的序列化的字节流。暴露在你的DataContract一个字节数组。这会给你的客户端(在DECOM pression和二进制反序列化)DataTable的一种高效,完全无损版本,而不是一个打了折扣的JSON版本的数据表中(如提供的(2))..

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?

解决方案

  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))...

这篇关于什么是最好的方式,JSON序列化WCF一个.NET数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆