Class JsonConverterFactory
- Namespace
- Codebelt.Extensions.Newtonsoft.Json
- Assembly
- Codebelt.Extensions.Newtonsoft.Json.dll
Provides a factory based way to create and wrap an Newtonsoft.Json.JsonConverter implementation.
public static class JsonConverterFactory
- Inheritance
-
JsonConverterFactory
Examples
Creating custom JSON converters typically requires subclassing JsonConverter<T> and overriding WriteJson and ReadJson methods, which introduces boilerplate code and tight coupling to the converter base class. For simple conversions that don't require complex state management, full subclassing is overkill. The JsonConverterFactory provides a lightweight factory pattern that creates converters from simple delegate functions—one for writing objects to JSON and one for reading from JSON. This enables ad-hoc converter creation without subclassing, supporting quick customization for domain-specific types, legacy formats, and compatibility scenarios. This example demonstrates creating a custom converter for a coordinate type:
using System;
using System.Globalization;
using Codebelt.Extensions.Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Examples;
public class Coordinate
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public Coordinate() { }
public Coordinate(double latitude, double longitude)
{
Latitude = latitude;
Longitude = longitude;
}
}
public class ConverterFactoryExample
{
static void Main()
{
// Create a converter that serializes Coordinate as "lat,lng"
var converter = JsonConverterFactory.Create<Coordinate>(
writer: (jw, coord, serializer) =>
{
jw.WriteValue($"{coord.Latitude:F4},{coord.Longitude:F4}");
},
reader: (jr, type, currentValue, serializer) =>
{
if (jr.TokenType == JsonToken.String && jr.Value is string coordStr)
{
var parts = coordStr.Split(',');
if (parts.Length == 2 &&
double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var lat) &&
double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var lng))
{
return new Coordinate(lat, lng);
}
}
return currentValue;
}
);
var settings = new JsonSerializerSettings();
settings.Converters.Add(converter);
var location = new Coordinate(51.5074, -0.1278); // London
var json = JsonConvert.SerializeObject(location, settings);
Console.WriteLine($"Serialized coordinate: {json}");
var deserialized = JsonConvert.DeserializeObject<Coordinate>(json, settings);
Console.WriteLine($"Deserialized: Latitude={deserialized.Latitude}, Longitude={deserialized.Longitude}");
}
}
The JsonConverterFactory accepts write and read delegates that implement custom serialization logic for a specific type. The factory creates a JsonConverter instance that can be registered in JsonSerializerSettings.Converters and will intercept serialization and deserialization of that type using the provided delegates.
Methods
Create(JsonConverter)
Creates a dynamic instance of converter.
public static JsonConverter Create(JsonConverter converter)
Parameters
converterJsonConverterThe Newtonsoft.Json.JsonConverter to wrap.
Returns
- JsonConverter
An Newtonsoft.Json.JsonConverter implementation of Type.
Create(Func<Type, bool>, Action<JsonWriter, object, JsonSerializer>, Func<JsonReader, Type, object, JsonSerializer, object>)
Creates a dynamic instance of an Newtonsoft.Json.JsonConverter implementation wrapping CanConvert(Type) through predicate, Newtonsoft.Json.JsonConverter.WriteJson(Newtonsoft.Json.JsonWriter, object, Newtonsoft.Json.JsonSerializer) through writer and ReadJson(JsonReader, Type, object, JsonSerializer) through reader.
public static JsonConverter Create(Func<Type, bool> predicate, Action<JsonWriter, object, JsonSerializer> writer = null, Func<JsonReader, Type, object, JsonSerializer, object> reader = null)
Parameters
predicateFunc<Type, bool>The function delegate that validates if given Type can be converted to and from JSON.
writerAction<JsonWriter, object, JsonSerializer>The delegate that converts a given Type to its JSON representation.
readerFunc<JsonReader, Type, object, JsonSerializer, object>The function delegate that generates Type from its JSON representation.
Returns
- JsonConverter
An Newtonsoft.Json.JsonConverter implementation of Type.
Create(Type, Action<JsonWriter, object, JsonSerializer>, Func<JsonReader, Type, object, JsonSerializer, object>)
Creates a dynamic instance of an Newtonsoft.Json.JsonConverter implementation wrapping Newtonsoft.Json.JsonConverter.WriteJson(Newtonsoft.Json.JsonWriter, object, Newtonsoft.Json.JsonSerializer) through writer and ReadJson(JsonReader, Type, object, JsonSerializer) through reader.
public static JsonConverter Create(Type objectType, Action<JsonWriter, object, JsonSerializer> writer = null, Func<JsonReader, Type, object, JsonSerializer, object> reader = null)
Parameters
objectTypeTypeThe type of the object to convert.
writerAction<JsonWriter, object, JsonSerializer>The delegate that converts
objectTypeto its JSON representation.readerFunc<JsonReader, Type, object, JsonSerializer, object>The function delegate that generates
objectTypefrom its JSON representation.
Returns
- JsonConverter
An Newtonsoft.Json.JsonConverter implementation of
objectType.
Create<T>(Action<JsonWriter, T, JsonSerializer>, Func<JsonReader, Type, T, JsonSerializer, T>)
Creates a dynamic instance of an Newtonsoft.Json.JsonConverter implementation wrapping Newtonsoft.Json.JsonConverter.WriteJson(Newtonsoft.Json.JsonWriter, object, Newtonsoft.Json.JsonSerializer) through writer and ReadJson(JsonReader, Type, object, JsonSerializer) through reader.
public static JsonConverter Create<T>(Action<JsonWriter, T, JsonSerializer> writer = null, Func<JsonReader, Type, T, JsonSerializer, T> reader = null)
Parameters
writerAction<JsonWriter, T, JsonSerializer>The delegate that converts
Tto its JSON representation.readerFunc<JsonReader, Type, T, JsonSerializer, T>The function delegate that generates
Tfrom its JSON representation.
Returns
- JsonConverter
An Newtonsoft.Json.JsonConverter implementation of
T.
Type Parameters
TThe type to implement an Newtonsoft.Json.JsonConverter.
Create<T>(Func<Type, bool>, Action<JsonWriter, T, JsonSerializer>, Func<JsonReader, Type, T, JsonSerializer, T>)
Creates a dynamic instance of an Newtonsoft.Json.JsonConverter implementation wrapping Newtonsoft.Json.JsonConverter.WriteJson(Newtonsoft.Json.JsonWriter, object, Newtonsoft.Json.JsonSerializer) through writer and ReadJson(JsonReader, Type, object, JsonSerializer) through reader.
public static JsonConverter Create<T>(Func<Type, bool> predicate, Action<JsonWriter, T, JsonSerializer> writer = null, Func<JsonReader, Type, T, JsonSerializer, T> reader = null)
Parameters
predicateFunc<Type, bool>The function delegate that validates if given Type can be converted to and from JSON.
writerAction<JsonWriter, T, JsonSerializer>The delegate that, when
predicatereturns true, convertsTto its JSON representation.readerFunc<JsonReader, Type, T, JsonSerializer, T>The function delegate that, when
predicatereturns true, generatesTfrom its JSON representation.
Returns
- JsonConverter
An Newtonsoft.Json.JsonConverter implementation of
T.
Type Parameters
TThe type to implement an Newtonsoft.Json.JsonConverter.