在 WCF 中 JSON 序列化 .NET DataTable 的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17928513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:22:46  来源:igfitidea点击:

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

.netjsonwcfserializationjson.net

提问by rhyno

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.

当我将 WCF 配置为使用 jSON 序列化并在我的一个 DataContracts 中包含一个 DataTable 时,它​​会在将整个 DataContract 序列化为 jSON 之前将 DataTable 序列化为 XML。我希望将 DataTable 序列化为 jSON,而不是 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 序列化为 XML?
  2. 我怎样才能让它序列化为 json 呢?

采纳答案by Keith Blows

  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.NETor FastJSONto 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.

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

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

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

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

回答by MUHAMMED IQBAL PA

Try this:

尝试这个:

public string ConvertDataTabletoString(System.Data.DataTable dt)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;
    foreach (System.Data.DataRow dr in dt.Rows)
    {
        row = new Dictionary<string, object>();
        foreach (System.Data.DataColumn col in dt.Columns)
        {
            row.Add(col.ColumnName, dr[col]);
        }
        rows.Add(row);
    }
    return serializer.Serialize(rows);
}

回答by YaBoiSandeep

I had same issue, my wcf service was not formatting the json properly while converting it from Dataset to Json. I got it working by using the following solution:

我有同样的问题,我的 wcf 服务在将它从数据集转换为 Json 时没有正确格式化 json。我通过使用以下解决方案使其工作:

using System.ServiceModel.Channels;
using System.ServiceModel.Web;

dsData is my Dataset

dsData 是我的数据集

string json = Newtonsoft.Json.JsonConvert.SerializeObject(dsData);
return WebOperationContext.Current.CreateTextResponse(json, "application/json;charset=utf-8", System.Text.Encoding.UTF8);

and "Message" will be the return type.

和“消息”将是返回类型。

回答by ladenedge

According to the chart on its homepage, Json.NETis really your only option - you can quickly get it from NuGet. Fortunately it's a great library and very easy to use.

根据其主页上的图表,Json.NET确实是您唯一的选择——您可以从NuGet快速获取它。幸运的是,它是一个很棒的库并且非常易于使用。

string json = JsonConvert.SerializeObject(myDataSet, new DataSetConverter());

Note that Rich Strahlhas a great post with more details, and he also includes some custom work he did to use JavaScriptSerializerwith (rather extensive) custom converters for the sake of comparison.

请注意,Rich Strahl有一篇很棒的帖子,其中包含更多详细信息,并且JavaScriptSerializer为了进行比较,他还包含了一些他与(相当广泛的)自定义转换器一起使用的自定义工作。