using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace ReZero.SuperAPI { /// /// Provides helper methods for JSON serialization and deserialization. /// public static class JsonHelper { public static readonly JsonSerializerSettings DefaultJsonSerializerSettings = new JsonSerializerSettings { Converters = new List { new StringLongConverter() }, // Other settings... }; /// /// Serializes an object to a JSON string. /// /// The object to serialize. /// /// The JSON string representation of the object. public static string SerializeObject(object obj, JsonSerializerSettings? settings = null) { return JsonConvert.SerializeObject(obj, settings ?? DefaultJsonSerializerSettings); } } /// /// Converts a string or integer to a long value during JSON serialization and deserialization. /// public class StringLongConverter : JsonConverter { /// /// Determines whether this converter can convert the specified object type. /// /// The type of the object to convert. /// true if the converter can convert the specified type; otherwise, false. public override bool CanConvert(Type objectType) { return objectType == typeof(long); } /// /// Writes the JSON representation of the object. /// /// The JSON writer. /// The value to write. /// The JSON serializer. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { writer.WriteValue(value?.ToString()); } /// /// Reads the JSON representation of the object. /// /// The JSON reader. /// The type of the object to convert. /// The existing value of the object being read. /// The JSON serializer. /// The deserialized object. public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.String) { // Parse the value as a long if it is a string in the JSON if (long.TryParse(reader.Value?.ToString(), out long result)) { return result; } else { throw new JsonSerializationException($"Unable to parse '{reader.Value}' as long."); } } else if (reader.TokenType == JsonToken.Integer) { // Convert the value directly to long if it is an integer in the JSON return Convert.ToInt64(reader.Value); } else { throw new JsonSerializationException($"Unexpected token type: {reader.TokenType}"); } } } }