CamelCaseElementNameConvention.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Reflection;
  17. namespace MongoDB.Bson.Serialization.Conventions
  18. {
  19. /// <summary>
  20. /// A convention that sets the element name the same as the member name with the first character lower cased.
  21. /// </summary>
  22. public class CamelCaseElementNameConvention : ConventionBase, IMemberMapConvention
  23. {
  24. // public methods
  25. /// <summary>
  26. /// Applies a modification to the member map.
  27. /// </summary>
  28. /// <param name="memberMap">The member map.</param>
  29. public void Apply(BsonMemberMap memberMap)
  30. {
  31. string name = memberMap.MemberName;
  32. name = GetElementName(name);
  33. memberMap.SetElementName(name);
  34. }
  35. // private methods
  36. private string GetElementName(string memberName)
  37. {
  38. if (memberName.Length == 0)
  39. {
  40. return "";
  41. }
  42. else if(memberName.Length == 1)
  43. {
  44. return Char.ToLowerInvariant(memberName[0]).ToString();
  45. }
  46. else
  47. {
  48. return Char.ToLowerInvariant(memberName[0]) + memberName.Substring(1);
  49. }
  50. }
  51. }
  52. }