• MongoDB数据实体中的ObjectId序列化成json的一个小坑


      很多时候我们都需要对实体对象进行序列化与反序列化,而ObjectId类型,只能用mongo的驱动以bson格式来序列化,但我们对外的交互,一般是json格式.

    有两种解决方案:

      1.自己写一个json.net的ObjectIdConverter来针对ObjectId,适用于json.net

      2.增加string类型的中间变量IdStr ,优点是适用于所有情况,比如mvc自带的序列化工具等 

    测试代码如下:

      1  [TestClass]
      2     public class MongoTest
      3     {
      4         [TestMethod()]
      5         public void Temp1()
      6         {
      7             var entity = new MyEntity()
      8             {
      9                 Id = new ObjectId("555afe4204cbee061cc31b6f"),
     10                 Name = "ZhangSan"
     11             };
     12             var str = JsonConvert.SerializeObject(entity);//{"Id":"555afe4204cbee061cc31b6f","Name":"ZhangSan"}
     13             var entity1 = JsonConvert.DeserializeObject<MyEntity>(str);
     14         }
     15 
     16         [TestMethod()]
     17         public void Temp2()
     18         {
     19             var entity = new MyEntity2()
     20             {
     21                 Id = new ObjectId("555afe4204cbee061cc31b6f"),
     22                 Name = "ZhangSan"
     23             };
     24             var str = JsonConvert.SerializeObject(entity); //{"IdStr":"555afe4204cbee061cc31b6f","Name":"ZhangSan"}
     25             var entity2 = str.FromJson<MyEntity2>();
     26         }
     27 
     28         [TestMethod()]
     29         public void Temp3()
     30         {
     31             var entity = new MyEntity3()
     32             {
     33                 Id = new ObjectId("555afe4204cbee061cc31b6f"),
     34                 Name = "ZhangSan"
     35             };
     36             var str = JsonConvert.SerializeObject(entity); //{"Id":"555afe4204cbee061cc31b6f","Name":"ZhangSan"}
     37             var entity2 = str.FromJson<MyEntity3>();
     38         }
     39     }
     40 
     41     public class MyEntity
     42     {
     43         public virtual ObjectId Id { get; set; }
     44         public virtual string Name { get; set; }
     45     }
     46    
     47     public class MyEntity2 : MyEntity
     48     {
     49         [JsonIgnore]
     50         public override  ObjectId Id { get; set; }
     51 
     52         [BsonIgnore]
     53         public string IdStr
     54         {
     55             get
     56             {
     57                 return Id.ToString();
     58             }
     59             set
     60             {
     61                 ObjectId id;
     62                 ObjectId.TryParse(value, out id);
     63                 Id = id;
     64             }
     65         }
     66     }
     67 
     68     public class MyEntity3 : MyEntity
     69     {
     70         [JsonConverter(typeof(ObjectIdConverter))]
     71         public override ObjectId Id { get; set; }
     72     }
     73     public class ObjectIdConverter : JsonConverter
     74     {
     75         public override bool CanConvert(Type objectType)
     76         {
     77             return objectType == typeof(ObjectId);
     78         }
     79 
     80         public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
     81         {
     82             if (reader.TokenType != JsonToken.String)
     83             {
     84                 throw new Exception(
     85                     String.Format("Unexpected token parsing ObjectId. Expected String, got {0}.",
     86                                   reader.TokenType));
     87             }
     88 
     89             var value = (string)reader.Value;
     90             return String.IsNullOrEmpty(value) ? ObjectId.Empty : new ObjectId(value);
     91         }
     92 
     93         public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
     94         {
     95             if (value is ObjectId)
     96             {
     97                 var objectId = (ObjectId)value;
     98 
     99                 writer.WriteValue(objectId != ObjectId.Empty ? objectId.ToString() : String.Empty);
    100             }
    101             else
    102             {
    103                 throw new Exception("Expected ObjectId value.");
    104             }
    105         }
    106     }
  • 相关阅读:
    火车进出栈问题(卡特兰数)
    HDU 4699 Editor (对顶栈)
    HDU 6430 TeaTree (线段树合并)
    Exam 4895 Crowd Control
    Exam 4894 Booming Business
    8377: Playoff
    hdu 6345 Problem J. CSGO
    HDU 6437 Problem L.Videos
    Making the Grade
    poj2279——Mr. Young's Picture Permutations
  • 原文地址:https://www.cnblogs.com/suijing/p/4646118.html
Copyright © 2020-2023  润新知