JSON Serialization with H.Necessaire.Serialization
Result-friendly JSON helpers over Newtonsoft.Json, plus AbstractConverter for interfaces.
Applies to H.Necessaire 4.0.5.
H.Necessaire.Serialization is a thin, friendly layer over Newtonsoft.Json. It gives you a handful of string extensions that fit the library's OperationResult style, so a bad JSON string becomes a result you can inspect instead of an exception.
Install
dotnet add package H.Necessaire.SerializationThe package targets netstandard2.0 and depends on Newtonsoft.Json 13.0.4. The runtime packages already reference it.
The extensions
using H.Necessaire.Serialization;
string json = order.ToJsonObject(); // null stays null
string pretty = order.ToJsonObject(isPrettyPrinted: true);
string list = orders.ToJsonArray();
Order a = json.JsonToObject<Order>(); // fallback on failure
OperationResult<Order> b = json.TryJsonToObject<Order>(); // result with the reason
| Method | Behaviour |
|---|---|
ToJsonObject<T>(defaultTo, isPrettyPrinted) | Serializes the value. Returns defaultTo (null unless you pass one) when the value is null. |
ToJsonArray<T>(defaultTo, isPrettyPrinted) | Serializes a sequence. Returns defaultTo when the sequence is null or empty. |
JsonToObject<T>(defaultTo) | Deserializes. On empty or invalid JSON it silently returns defaultTo. |
TryJsonToObject<T>(defaultTo) | Same, but returns an OperationResult<T>: failed with “The JSON string is empty” or the parsing exception, with defaultTo as the payload. |
DeserializeToNotes(defaultTo) | Reads a Note[] from either an array of notes or a plain { "key": "value" } object. |
Two things to watch
- An empty list serializes to
null, not"[]". If a consumer expects an array, passdefaultTo: "[]". JsonToObjecthides failures by design. When corrupt input must not pass silently, useTryJsonToObjectand checkIsSuccessful.
These methods call Newtonsoft with its default settings: there is no overload for custom JsonSerializerSettings. If you need camelCase, a custom date format and so on, call JsonConvert directly for those cases.
Handling interfaces and abstract types
Newtonsoft can't deserialize an interface on its own. AbstractConverter<TAbstract, TConcrete> tells it which concrete type to build:
public class Drawing
{
[JsonConverter(typeof(AbstractConverter<IShape, Circle>))]
public IShape Shape { get; set; }
}
Drawing drawing = json.JsonToObject<Drawing>();It converts only values declared as TAbstract and always reads them as TConcrete, so it suits properties with exactly one implementation in practice.
Where the library uses it
- Sync:
SyncRequest.Payloadis JSON, andSyncRequestProcessorBaseparses it withJsonToObject/TryJsonToObject. - Auditing: snapshots are stored as JSON, and
JsonAuditEntryandJsonFileAuditEntryread them back lazily. - QD actions: the
Payloadstring is yours to fill with JSON; serialize on the way in and parse in the processor.
// Queueing
await qer.Queue(QdAction.New("SendWelcomeEmail", new { userId = 42 }.ToJsonObject()));
// In the processor
protected override async Task<OperationResult> ProcessQdAction(QdAction action)
{
OperationResult<WelcomeEmailJob> job = action.Payload.TryJsonToObject<WelcomeEmailJob>();
if (!job.IsSuccessful)
return job;
return await mailer.SendAsync(job.Payload);
}