2014-07-18 4 views
2

사용자 정의 직렬 변환기를 작성한 특성으로서 오브젝트가 있습니다. 내 컬렉션에서 데이터를 문자열로 나타내려고하기 때문에 ToString 만 호출하면됩니다.오브젝트에 Mongodb 문자열 비 직렬화

cm.MapMember(c => c.myObjectProperty).SetSerializer(new ObjectToStringSerializer()); 

위의 데이터는 한 번만 호출되며 데이터를 저장할 때 잘 작동합니다. 예상대로 문자열 값을 가진 부모 개체를 볼 수 있습니다.

여기 기본 시리얼입니다 :

public class ObjectToStringSerializer : IBsonSerializer { 


     #region IBsonSerializer Members 

     public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) 
     { 
      if (bsonReader.State == MongoDB.Bson.IO.BsonReaderState.Type && bsonReader.CurrentBsonType != MongoDB.Bson.BsonType.Null) 
       return Activator.CreateInstance(nominalType, new object[] { bsonReader.ReadString() }); 
      return null; 
     } 

     public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) 
     { 

      if(bsonReader.State == MongoDB.Bson.IO.BsonReaderState.Type && bsonReader.CurrentBsonType != MongoDB.Bson.BsonType.Null) 
       return Activator.CreateInstance(nominalType, new object[] { bsonReader.ReadString() }); 
      return null; 
     } 

     public IBsonSerializationOptions GetDefaultSerializationOptions() 
     { 
      throw new NotImplementedException(); 
     } 

     public void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) 
     { 


      if (value != null) 
      { 
       bsonWriter.WriteString(value.ToString()); 
      } 
      else 
       bsonWriter.WriteNull(); 

     } 

     #endregion 
    } 

나는 예외가 발생 컬렉션에서 다시 부모 객체를 취득 할 때 :

국가가 입력 될 때 ReadBsonType 만 호출 할 수 있습니다

, 국가가 가치 일 때가 아닙니다.

스택 추적은 사용자 지정 serializer의 deserialize 메서드를 호출하려고 시도하는 것처럼 보이지 않습니다.

나는 deserialize 메서드를 호출하기 위해 무엇을 놓치고 있습니까? 나는 간단한 serialization 공급자를 추가하려고 시도했지만 올바르게 생각하지 않는다. 나는 또한 serializer를 regstering 시도했다.

BsonSerializer.RegisterSerializer(typeof(myObjectPropertyType), new ObjectToStringSerializer()); 

답변

2

문제는 Deserialize 멤버에 대한 내 조건이었습니다.

if (bsonReader.State == MongoDB.Bson.IO.BsonReaderState.Type && bsonReader.CurrentBsonType != MongoDB.Bson.BsonType.Null) 

작성자에게 전화를 건 적이 없습니다. 변경된 항목 :

if (bsonReader.State == MongoDB.Bson.IO.BsonReaderState.Value && bsonReader.CurrentBsonType == MongoDB.Bson.BsonType.String) 
관련 문제