C
C#12mo ago
SWEETPONY

✅ How to serialize IEnumerable<T> to json?

I have following:
public IReadOnlyList<MessageQueueConsumeResultHeader>? Headers { get; init; }

public abstract class MessageQueueConsumeResultHeader
{
public abstract string Key { get; }

public abstract byte[] GetValueBytes();

public override string ToString()
{
return this.Key + " (" + string.Join<byte>(",", (IEnumerable<byte>) this.GetValueBytes()) + ")";
}
}
public IReadOnlyList<MessageQueueConsumeResultHeader>? Headers { get; init; }

public abstract class MessageQueueConsumeResultHeader
{
public abstract string Key { get; }

public abstract byte[] GetValueBytes();

public override string ToString()
{
return this.Key + " (" + string.Join<byte>(",", (IEnumerable<byte>) this.GetValueBytes()) + ")";
}
}

and I want to get following: " { "Key": "GetValueBytes()", ... } "
how can I do it?
16 Replies
SWEETPONY
SWEETPONYOP12mo ago
I can do this:
public static class MessageQueueConsumeResultHeaderExtensions
{
public static string ToJson(this IReadOnlyList<MessageQueueConsumeResultHeader>? headers)
{
if (headers == null || headers.Count == 0)
{
return "{}";
}

var result = new StringBuilder();
result.AppendLine("{");
foreach (var header in headers)
{
result.AppendLine($" \"{header.Key}\": \"{string.Join(",", header.GetValueBytes())}\",");
}
result.Length--; // Remove the trailing comma
result.AppendLine("}");
return result.ToString();
}
}
public static class MessageQueueConsumeResultHeaderExtensions
{
public static string ToJson(this IReadOnlyList<MessageQueueConsumeResultHeader>? headers)
{
if (headers == null || headers.Count == 0)
{
return "{}";
}

var result = new StringBuilder();
result.AppendLine("{");
foreach (var header in headers)
{
result.AppendLine($" \"{header.Key}\": \"{string.Join(",", header.GetValueBytes())}\",");
}
result.Length--; // Remove the trailing comma
result.AppendLine("}");
return result.ToString();
}
}
but it looks bad
Chiyoko_S
Chiyoko_S12mo ago
JsonConverter serializes dictionaries as key-value pairs just fine so perhaps make the collection type into a dictionary? cleaner way would be to write a custom converter otherwise
cap5lut
cap5lut12mo ago
iirc IEnumerable<byte> will be serialized into a json array of numbers, byte[] will result in a base64 encoded string, the proper answer is a custom converter
Chiyoko_S
Chiyoko_S12mo ago
no I meant something on the line of exposing Headers as IReadOnlyDictionary<string, byte[]>
cap5lut
cap5lut12mo ago
yeah, that would result in "header1": "base64-encoded-byte-array", while ⤴️ would be "header1": "1,254,4,6,127"
Chiyoko_S
Chiyoko_S12mo ago
ahhh so they do want it as a comma-separated list of values why though you'd need a custom converter then why though
cap5lut
cap5lut12mo ago
tbh i like neither variant 😂 i would prefer a simple hex string without delimiters for such stuff, but i guess base64 is at least not that a** long
Chiyoko_S
Chiyoko_S12mo ago
hex string would get much longer than base64! and I don't think it really adds any benefit apart from being easy to parse, so... why?
cap5lut
cap5lut12mo ago
i was working on a project for a long time where i had to write some test packets (had to do with reverse engineering a network protocol), guess i got used to hex in json because of that was a lot of fiddling around, adding similar packets (if it were stored binary i would have taken a hex editor for that), where u simply edited the description, some bytes and that was it later the guy i did work together on that wrote a whole GUI tool and stored the whole thing as binary blob but also with some more helpful visualization on the data
SWEETPONY
SWEETPONYOP12mo ago
unfortunately I can't change IEnumerable to IReadOnlyDictionary catshy hm maybe I can do smth like.. Headers.ToDictionary(header => header.Key, header => header.GetValueBytes())
var map = context.Headers?.ToDictionary(x => x.Key, x => x.GetValueBytes());
var result = JsonSerializer.Serialize(map);
var map = context.Headers?.ToDictionary(x => x.Key, x => x.GetValueBytes());
var result = JsonSerializer.Serialize(map);
Chiyoko_S
Chiyoko_S12mo ago
I would suggest using a custom converter
Chiyoko_S
Chiyoko_S12mo ago
are you using S.T.Json?
Unknown User
Unknown User12mo ago
Message Not Public
Sign In & Join Server To View
Chiyoko_S
Chiyoko_S12mo ago
How to write custom converters for JSON serialization - .NET
Learn how to create custom converters for the JSON serialization classes that are provided in the System.Text.Json namespace.
SWEETPONY
SWEETPONYOP12mo ago
ok, thanks!

Did you find this page helpful?