将代码转换为使用JSON.net而不是system . runtime . serializer . datacontr

本文关键字:system runtime datacontr serializer net 转换 代码 JSON | 更新日期: 2023-09-27 18:10:29

如何在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;

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

谢谢:-)

将代码转换为使用JSON.net而不是system . runtime . serializer . datacontr

使用JSON。. NET中,序列化时不需要该类型。我假设它能自己计算出你要传递的类型。

你可以完全去掉这个

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

然后改成

serializer.WriteObject(compress, objList);

:

var json = JsonConvert.SerializeObject(objList);

JSON。JsonConvert. Net文档

我相信你可以使用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;
  }
相关文章: