Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting MemoryStream to String with JSON

Tags:

c#

.net-core

I'm having difficulty using using MemoryStream to manage strings.

Specifically, I'm playing with JSON without using built in serialisation/deserialisation methods.

When using NewtonSoft JSON writer, it's simple enough and it takes a TextWriter so writing is something like this with a string builder:

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        using (newton.JsonWriter writer=new newton.JsonTextWriter(sw))
        {
            writer.WriteStartObject();
            writer.WritePropertyName("Name");
            writer.WriteValue("Neil");
            writer.WriteEnd();
            writer.Flush();
            System.Console.WriteLine(sb.ToString());
        }

But when I'm trying to use the new .net Core 3.x, it doesn't take a TextWriter, but a Stream or IBufferWriter. Not exactly knowing how to use the IBufferWriter, the only way I could get it to convert the stream to a string was the following, which seems quite clunky in comparison. Is there a better way than setting the position, creating a new reader and reading to end as below?

Either a better way to convert memory stream to string or using IBufferWriter?

        MemoryStream ms = new MemoryStream();
        System.Text.Json.Utf8JsonWriter writer = new Utf8JsonWriter(ms);
        writer.WriteStartObject();
        writer.WritePropertyName("Name");
        writer.WriteStringValue("Neil");
        writer.WriteEndObject();
        writer.Flush();
        ms.Position = 0;
        string output = new StreamReader(ms).ReadToEnd();
        Console.WriteLine(output);

thanks.

like image 674
Neil Avatar asked Jun 27 '26 04:06

Neil


1 Answers

You can just call ToArray on the memory stream to turn it into an array of UTF-8 bytes, which can then be converted to a string with Encoding.UTF8.GetString:

var ms = new MemoryStream();
Utf8JsonWriter writer = new Utf8JsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("Name");
writer.WriteStringValue("Neil");
writer.WriteEndObject();
writer.Flush();
ms.Close();
Console.WriteLine(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
like image 196
Sweeper Avatar answered Jun 29 '26 20:06

Sweeper