0

如何在 JSON.net 中进行等效操作?

 public SerializedResults SerializeResults(Type queryType, IEnumerable entities)
      {
          var results = SerializeDynamicType(queryType);

          var objList = AnonymousFns.DeconstructMany(entities, false, queryType).ToList();

          var ms = new MemoryStream();
          var type = objList.GetType();
          var serializer = new DataContractSerializer(type);

          using (ms)
          {
              using (GZipStream compress = new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression))
              {
                  serializer.WriteObject(compress, objList);
              }
          }

          results.ByteArray = ms.ToArray();

          return results;
      }

我特别对这一行感到困惑: var serializer = new DataContractSerializer(type);

你如何在 JSON.NET 中做到这一点?

谢谢 :-)

4

2 回答 2

1

使用 JSON.NET,序列化时不需要类型。我假设它可以自行计算出您传入的类型。

所以,你可以完全摆脱这个:

var type = objList.GetType();
var serializer = new DataContractSerializer(type);

并改变这个:

serializer.WriteObject(compress, objList);

到:

var json = JsonConvert.SerializeObject(objList);

这是 JsonConvert 的 JSON.Net文档

于 2013-04-23T22:17:17.040 回答
0

我相信您可以使用 BsonWriter 写入流。我不确定它是否会为您提供与以前完全相同的二进制格式,但在概念上它是相同的。

  public SerializedResults SerializeResults(Type queryType, IEnumerable entities)
  {
      var results = SerializeDynamicType(queryType);

      var objList = AnonymousFns.DeconstructMany(entities, false, queryType).ToList();

      var ms = new MemoryStream();         

      using (ms)
      {
          using (GZipStream compress = new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression))
          {
            using( BsonWriter writer = new BsonWriter(compress))
            {
              JsonSerializer serializer = new JsonSerializer();                 
              serializer.Serialize(writer, objList);
            }
          }
      }

      results.ByteArray = ms.ToArray();

      return results;
  }
于 2013-04-23T22:31:07.823 回答