在 WCF 中 JSON 序列化 .NET DataTable 的最佳方法是什么? [英] What's the best way to jSON serialize a .NET DataTable in WCF?

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

问题描述

当我将 WCF 配置为使用 jSON 序列化并在我的一个 DataContracts 中包含一个 DataTable 时,它​​会在将整个 DataContract 序列化为 jSON 之前将 DataTable 序列化为 XML.我希望将 DataTable 序列化为 JSON,而不是 XML.

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.

我的问题是:

  1. 为什么它首先将 DataTable 序列化为 XML?
  2. 我怎样才能让它序列化为 JSON?

推荐答案

  1. DataTable 是一个纯 .NET 结构,不能(容易)用 JSON 以无损方式表示.DataTables 包含许多 JSON 无法存储的附加信息:主键、autoincs、允许空值、标题、数据类型、索引等. 序列化到 XML/Binary 是 DataTable 可以由 .NET 本地序列化的唯一方法.然后将此 XML 序列化的 DataTable 序列化为 JSON.

  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.

使用 JSON.NETFastJSON 将 DataTable 转换为简单、干净的 JSON 兼容版本的 DataTable,它可以被任何 JSON 使用客户端,而不仅仅是 .NET WCF 客户端.您将丢失上面 (1) 中提到的所有 DataTable 自定义属性,而只能获得字段名称/值 JSON 对.由于每行中的字段名称重复,因此这种方式的存储效率低下.

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.

不要在您的 DataContract 中使用 DataTable.如果您想要 DataTable 的好处并且您的客户端始终是 .NET,请通过 Binary Serialization 将 DataTable 序列化为字节数组,然后可选地压缩生成的序列化字节流.在您的 DataContract 中公开一个字节数组.这将为您提供一个高效的、完全无损的客户端 DataTable 版本(在解压和二进制反序列化之后),而不是一个淡化的 JSON 版本的 DataTable(由 (2) 提供)...

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

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

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