public static Object serializeField ( ObjectMapper objectMapper , Object value ) { if ( value == null || BASIC_TYPES . contains ( value . getClass ( ) ) ) { // Return as is return value ; } else if ( value instanceof DBObject ) { return serializeFields ( objectMapper , ( DBObject ) value ) ; } else if ( value instanceof Collection ) { Collection < ? > coll = ( Collection < ? > ) value ; List < Object > copy = null ; int position = 0 ; for ( Object item : coll ) { Object returned = serializeField ( objectMapper , item ) ; if ( returned != item ) { if ( copy == null ) { copy = new ArrayList < Object > ( coll ) ; } copy . set ( position , returned ) ; } position ++ ; } if ( copy != null ) { return copy ; } else { return coll ; } } else if ( value . getClass ( ) . isArray ( ) ) { if ( BASIC_TYPES . contains ( value . getClass ( ) . getComponentType ( ) ) ) { return value ; } Object [ ] array = ( Object [ ] ) value ; Object [ ] copy = null ; for ( int i = 0 ; i < array . length ; i ++ ) { Object returned = serializeField ( objectMapper , array [ i ] ) ; if ( returned != array [ i ] ) { if ( copy == null ) { copy = new Object [ array . length ] ; System . arraycopy ( array , 0 , copy , 0 , array . length ) ; } copy [ i ] = returned ; } } if ( copy != null ) { return copy ; } else { return array ; } } else { // We don't know what it is, serialise it BsonObjectGenerator generator = new BsonObjectGenerator ( ) ; try { objectMapper . writeValue ( generator , value ) ; } catch ( JsonMappingException e ) { throw new MongoJsonMappingException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( "Somehow got an IOException writing to memory" , e ) ; } return generator . getValue ( ) ; } }
Serialize the given field