Skip to content

Commit

Permalink
Convert to snake case when serializing
Browse files Browse the repository at this point in the history
  • Loading branch information
Erik Bylund authored and kirre-bylund committed Dec 15, 2023
1 parent ec615a7 commit 7ea7906
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions Runtime/Libraries/ZeroDepJson/ZeroDepJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

#pragma warning disable IDE0063 // Use simple 'using' statement
Expand Down Expand Up @@ -3064,6 +3065,15 @@ private static bool EqualsIgnoreCase(this string str, string text, bool trim = f
return string.Compare(str, text, StringComparison.OrdinalIgnoreCase) == 0 || /*Recover from different casing (Snake_Case to CamelCase)*/ string.Compare(str, text.Replace("_", ""), StringComparison.OrdinalIgnoreCase) == 0;
}

private static string ConvertToSnakeCase(string str)
{
str = Regex.Replace(str, @"([a-z])([A-Z])", "$1_$2");
str = Regex.Replace(str, @"([a-z])([0-9])", "$1_$2");
str = Regex.Replace(str, @"([0-9])([A-Za-z])", "$1_$2");
str = Regex.Replace(str, @"([A-Z]{2,})([a-z])", "$1_$2");
return str.ToLowerInvariant();
}

private static string Nullify(this string str)
{
if (str == null)
Expand Down Expand Up @@ -3274,14 +3284,15 @@ public void WriteValues(TextWriter writer, object component, IDictionary<object,
}
else
{
string nameToWrite = options.SerializationOptions.HasFlag(JsonSerializationOptions.ConvertToSnakeCase) ? ConvertToSnakeCase(member.EscapedWireName) : member.EscapedWireName; ;
if (options.SerializationOptions.HasFlag(JsonSerializationOptions.WriteKeysWithoutQuotes))
{
writer.Write(member.EscapedWireName);
writer.Write(nameToWrite);
}
else
{
writer.Write('"');
writer.Write(member.EscapedWireName);
writer.Write(nameToWrite);
writer.Write('"');
}

Expand Down Expand Up @@ -5498,10 +5509,15 @@ public enum JsonSerializationOptions
/// </summary>
SkipGetOnly = 0x800000,

/// <summary>
/// Convert field names to snake case.
/// </summary>
ConvertToSnakeCase = 0x1000000,

/// <summary>
/// The default value.
/// </summary>
Default = UseXmlIgnore | UseScriptIgnore | SerializeFields | AutoParseDateTime | UseJsonAttribute | SkipGetOnly | SkipNullPropertyValues | SkipNullDateTimeValues,
Default = UseXmlIgnore | UseScriptIgnore | SerializeFields | AutoParseDateTime | UseJsonAttribute | SkipGetOnly | SkipNullPropertyValues | SkipNullDateTimeValues | ConvertToSnakeCase,
}

/// <summary>
Expand Down

0 comments on commit 7ea7906

Please sign in to comment.