JsonDefaults.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Text.Json;
  2. using System.Text.Json.Serialization;
  3. using MediaBrowser.Common.Json.Converters;
  4. namespace MediaBrowser.Common.Json
  5. {
  6. /// <summary>
  7. /// Helper class for having compatible JSON throughout the codebase.
  8. /// </summary>
  9. public static class JsonDefaults
  10. {
  11. /// <summary>
  12. /// Gets the default <see cref="JsonSerializerOptions" /> options.
  13. /// </summary>
  14. /// <remarks>
  15. /// When changing these options, update
  16. /// Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
  17. /// -> AddJellyfinApi
  18. /// -> AddJsonOptions.
  19. /// </remarks>
  20. /// <returns>The default <see cref="JsonSerializerOptions" /> options.</returns>
  21. public static JsonSerializerOptions GetOptions()
  22. {
  23. var options = new JsonSerializerOptions
  24. {
  25. ReadCommentHandling = JsonCommentHandling.Disallow,
  26. WriteIndented = false
  27. };
  28. options.Converters.Add(new JsonGuidConverter());
  29. options.Converters.Add(new JsonInt32Converter());
  30. options.Converters.Add(new JsonStringEnumConverter());
  31. options.Converters.Add(new JsonNonStringKeyDictionaryConverterFactory());
  32. return options;
  33. }
  34. /// <summary>
  35. /// Gets camelCase json options.
  36. /// </summary>
  37. /// <returns>The camelCase <see cref="JsonSerializerOptions" /> options.</returns>
  38. public static JsonSerializerOptions GetCamelCaseOptions()
  39. {
  40. var options = GetOptions();
  41. options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
  42. return options;
  43. }
  44. /// <summary>
  45. /// Gets PascalCase json options.
  46. /// </summary>
  47. /// <returns>The PascalCase <see cref="JsonSerializerOptions" /> options.</returns>
  48. public static JsonSerializerOptions GetPascalCaseOptions()
  49. {
  50. var options = GetOptions();
  51. options.PropertyNamingPolicy = null;
  52. return options;
  53. }
  54. }
  55. }