0

Consider this sample code:

var ms = new MemoryStream();
                using (StreamWriter sw = new StreamWriter(ms))
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    this.GetSerializer().Serialize(writer, data, typeof(T));

                    // convert stream to string
                    ms.Position = 0;
                    var reader = new StreamReader(ms);
                    var textToSend = reader.ReadToEnd();
                }

Serializer obtained from this method:

private JsonSerializer GetSerializer()
        {
            var serializer = new JsonSerializer
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            serializer.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd\\THH:mm:ss.fffZ" });
            return serializer;
        }

When I serialize 'data' it produces memory stream with 7168 bytes and when I convert to string I see how message being truncated. Searched but can't find what might be causing this limit?

katit
  • 17,375
  • 35
  • 128
  • 256
  • 2
    You need to dispose the `JsonTextWriter` and `StreamWriter` before accessing the memory stream, both have buffers that need flushing. See: [JToken.WriteToAsync does not write to JsonWriter](https://stackoverflow.com/a/60916536/3744182) which shows an example of disposing the `StreamWriter` without having to dispose the underlying stream. – dbc May 12 '20 at 16:11
  • Like @dbc said, you should move your `MemorySteam` reading to after your 2 `using` blocks. The `MemoryStream` should technically also be in a `using` block of its own. At the end of that block is where I'd read from the stream. – itsme86 May 12 '20 at 16:12
  • Shall we close as a duplicate of [JToken.WriteToAsync does not write to JsonWriter](https://stackoverflow.com/a/60916536/3744182) since the answer is basically identical? – dbc May 12 '20 at 19:20
  • If you respond I can mark you q as answer – katit May 13 '20 at 19:44

0 Answers0