Internally, JsonConvert.SerializeObject(obj, Formatting.Indented)
boils down to
JsonSerializer jsonSerializer = JsonSerializer.Create(null);
StringWriter stringWriter = new StringWriter(new StringBuilder(256), (IFormatProvider) CultureInfo.InvariantCulture);
using (JsonTextWriter jsonTextWriter = new JsonTextWriter((TextWriter) stringWriter))
{
jsonTextWriter.Formatting = formatting;
jsonSerializer.Serialize((JsonWriter) jsonTextWriter, value);
}
return stringWriter.ToString();
This works just fine. However, if I do the following:
string json;
JsonSerializer jsonSerializer = JsonSerializer.Create();
using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
serializer.Serialize(jsonWriter, cmd);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
Then the value of json
is ""
. Can anyone point me to my mistake?
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.
Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.
The problem is that you haven't flushed the streamWriter
after writing:
serializer.Serialize(jsonWriter, cmd);
streamWriter.Flush();
stream.Position = 0;
Alternatively, why not just use a StringWriter
to start with?
using (var writer = new StringWriter())
{
using (var jsonWriter = new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, cmd);
Console.WriteLine(writer.ToString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With