Skip to content
Promote Your Product

Json Helper

Namespace: ZhonTai.Common.Helpers / ZhonTai.Common.Converters

A JSON serialization utility class built on System.Text.Json. Thread-safe with built-in custom converters for DateTime, Enum, and more.

Use Cases

  • API request/response serialization and deserialization
  • Configuration file reading
  • Cache data storage and retrieval
  • Log data formatting

Built-in Features

JsonHelper's default configuration includes:

FeatureDescription
Case-insensitivePropertyNameCaseInsensitive = true
Ignore commentsReadCommentHandling = Skip
Allow trailing commasAllowTrailingCommas = true
Cycle reference handlingReferenceHandler = IgnoreCycles
No Chinese escapingEncoder = UnsafeRelaxedJsonEscaping
Formatted outputWriteIndented = true

Custom Converters

ConverterDescription
DateTimeConverterDateTime conversion, supports string and numeric timestamp deserialization
NullableDateTimeConverterNullable DateTime conversion (DateTime?)
FlexibleEnumConverterFlexible enum conversion, supports both string and numeric serialization/deserialization

Examples

Serialization

csharp
using ZhonTai.Common.Helpers;

// Serialize an object
var user = new { Name = "John", Age = 25 };
var json = JsonHelper.Serialize(user);
// {"name":"John","age":25}

Deserialization

csharp
using ZhonTai.Common.Helpers;

// Deserialize to a strongly-typed object
var json = "{\"name\":\"John\",\"age\":25}";
var user = JsonHelper.Deserialize<UserDto>(json);

// Deserialize to a dynamic type
var obj = JsonHelper.Deserialize(json, typeof(UserDto));

Custom Options

csharp
using ZhonTai.Common.Helpers;
using System.Text.Json;

// Serialize with custom options
var options = new JsonSerializerOptions
{
    WriteIndented = false,
    PropertyNamingPolicy = null
};
var json = JsonHelper.Serialize(user, options);

Configure Global Options

csharp
using ZhonTai.Common.Helpers;

// Modify global default configuration (thread-safe)
JsonHelper.ConfigureOptions(options =>
{
    options.WriteIndented = false;
});

Get a Copy of Current Options

csharp
using ZhonTai.Common.Helpers;

// Get a copy of current global options without affecting the global state
var options = JsonHelper.GetCurrentOptions();
options.WriteIndented = false;
var json = JsonHelper.Serialize(user, options);

FlexibleEnumConverter - Enum Compatibility

FlexibleEnumConverter allows enum fields in JSON to use both string and numeric formats:

csharp
// Both JSON formats deserialize correctly
var json1 = "{\"status\":\"Enabled\"}";    // String format
var json2 = "{\"status\":1}";               // Numeric format

var result1 = JsonHelper.Deserialize<MyDto>(json1);
var result2 = JsonHelper.Deserialize<MyDto>(json2);