JSON
JSON is the default in both directions, but not in the same sense:
- Decode: an event without
datacontenttypeis read asapplication/json. - Encode: there is no default. The caller always passes the content type.
public sealed record Reading(string Sensor, decimal Value);
.Add<Reading>("application/json",
ce => JsonSerializer.Deserialize<Reading>((string)ce.Data!)!,
reading => new CloudEvent
{
Data = JsonSerializer.Serialize(reading),
DataContentType = "application/json",
})
The encoder sets only data, content type and (optionally) schema. Routing and the envelope are applied by the binding.
JSON and binary for the same value
var state = codec.Encode(value, "application/json");
var change = codec.Encode(value, OrderBookImage.ContentType);
That is the intended pattern for an order book: the saved state is JSON, the published event is FlatBuffers.