I'm consuming events from Azure Event Hub, and need to log the event payload as a string. The payload is in JSON format.
private readonly EventProcessorClient _eventProcessor;
_eventProcessor.ProcessEventAsync += ProcessMessage;
I've tried this:
private async Task ProcessMessage(ProcessEventArgs eventArgs)
{
string stringPayload1 = Encoding.UTF8.GetString(eventArgs.Data.Body.Span);
Console.WriteLine(stringPayload1);
string stringPayload2 = eventArgs.Data.EventBody.ToString(); // EventBody is BinaryData
Console.WriteLine(stringPayload2);
}
but in both cases they contain spaces. output:
{ "data": [ { "name": "cpuUsage", "value": "18" }, { "name": "cpuTemperature", "value": "49" }, { "name": "memoryUsage", "value": "24" }, { "name": "storageUsage", "value": "23" }, { "name": "storageHealth", "value": "90" } ], "datacontenttype": "application/json", "id": "cd31d925-b600-4d5b-89eb-25c30388ecce", "source": "/CCZ15A60022248000012", "specversion": "1.0", "time": "2023-08-15T12:21:08", "type": "telemetry"}
I need this compact output
{"data":[{"name":"cpuUsage","value":"18"},{"name":"cpuTemperature","value":"49"},{"name":"memoryUsage","value":"24"},{"name":"storageUsage","value":"23"},{"name":"storageHealth","value":"90"}],"datacontenttype":"application/json","id":"cd31d925-b600-4d5b-89eb-25c30388ecce","source":"/CCZ15A60022248000012","specversion":"1.0","time":"2023-08-15T12:21:08","type":"telemetry"}
There is no possibility to ask the producers they remove all spaces before sending.
Are there any ways to achieve that without string.Replace
?
Why the EventHub does not compress the JSON payload? It is inefficient because my message contains useless symbols that affect the message size
Just deserialize it and serialize it back. For example with System.Text.Json
(which by default writes data without extra whitespace, see JsonSerializerOptions.WriteIndented
) you can use JsonDocument
as "intermediate" type:
// or JsonSerializer.Deserialize<JsonDocument>(stringPayload1)
using var jdoc = JsonSerializer.Deserialize<JsonDocument>(eventArgs.Data.Body.Span);
var serialize = JsonSerializer.Serialize(jdoc);