JsonDefaults.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. /// Pascal case json profile media type.
  13. /// </summary>
  14. public const string PascalCaseMediaType = "application/json; profile=\"PascalCase\"";
  15. /// <summary>
  16. /// Camel case json profile media type.
  17. /// </summary>
  18. public const string CamelCaseMediaType = "application/json; profile=\"CamelCase\"";
  19. /// <summary>
  20. /// Gets the default <see cref="JsonSerializerOptions" /> options.
  21. /// </summary>
  22. /// <remarks>
  23. /// When changing these options, update
  24. /// Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
  25. /// -> AddJellyfinApi
  26. /// -> AddJsonOptions.
  27. /// </remarks>
  28. /// <returns>The default <see cref="JsonSerializerOptions" /> options.</returns>
  29. public static JsonSerializerOptions GetOptions()
  30. {
  31. var options = new JsonSerializerOptions
  32. {
  33. ReadCommentHandling = JsonCommentHandling.Disallow,
  34. WriteIndented = false,
  35. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
  36. NumberHandling = JsonNumberHandling.AllowReadingFromString
  37. };
  38. options.Converters.Add(new JsonGuidConverter());
  39. options.Converters.Add(new JsonStringEnumConverter());
  40. options.Converters.Add(new JsonNullableStructConverterFactory());
  41. return options;
  42. }
  43. /// <summary>
  44. /// Gets camelCase json options.
  45. /// </summary>
  46. /// <returns>The camelCase <see cref="JsonSerializerOptions" /> options.</returns>
  47. public static JsonSerializerOptions GetCamelCaseOptions()
  48. {
  49. var options = GetOptions();
  50. options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
  51. return options;
  52. }
  53. /// <summary>
  54. /// Gets PascalCase json options.
  55. /// </summary>
  56. /// <returns>The PascalCase <see cref="JsonSerializerOptions" /> options.</returns>
  57. public static JsonSerializerOptions GetPascalCaseOptions()
  58. {
  59. var options = GetOptions();
  60. options.PropertyNamingPolicy = null;
  61. return options;
  62. }
  63. }
  64. }