0

I'm using JSON.NET's JsonTextWriter as follows:

var writer = new StringWriter();
var textWriter = (TextWriter)writer;
var jsonTextWriter = new JsonTextWriter(textWriter);

jsonTextWriter.WriteNull();

var data = jsonTextWriter.ToString();

How can I achieve that data will be empty string instead of "null"?

Tomas Petovsky
  • 285
  • 4
  • 14
  • Your example has an error; you're assigning the type name of the `jsonTextWriter` to `data` instead of using the `StringWriter` – Jesse Squire Nov 12 '16 at 17:52
  • 1
    Don't call `WriteNull` if you don't want to write `null`? You're directly causing this. – usr Nov 12 '16 at 19:11
  • You could consider using inbuilt attributes in Json.Net, to achieve the same, check out, http://stackoverflow.com/a/15136173/1559611 – Mrinal Kamboj Nov 12 '16 at 19:22
  • @usr Yes, you are right :) I was missing something in my project so I asked this question, that is no longer valid for me now :) – Tomas Petovsky Nov 15 '16 at 17:18

1 Answers1

3

The behavior of the JsonTextWriter in this instance is correct; to represent a null value in JSON, the expected token is null. For example:

{
    "Name"    : "SomeGuy",
    "Address" : null
}

From your question, it seems that what you're looking to do is write an actual empty string to indicate a complete lack of value. You could do that by calling jsonTextWriter.WriteRaw(""). However, that will produce invalid JSON, as you'd end up with:

{
    "Name"    : "SomeGuy",
    "Address" : 
}

I'm guessing that isn't want you want, either. To emit an empty string that actually represents an empty string value in JSON, you'll want to do jsonTextWriter.WriteValue("") That will produce the expected "" token that I believe you are looking for, which would look like:

{
    "Name"    : "SomeGuy",
    "Address" : ""
}

As a full example, to emit the object that I've been using would be something like:

var writer = new StringWriter();
var textWriter = (TextWriter)writer;
var jsonTextWriter = new JsonTextWriter(textWriter);

jsonTextWriter.WriteStartObject();
jsonTextWriter.WritePropertyName("Name");
jsonTextWriter.WriteValue("SomeGuy");
jsonTextWriter.WritePropertyName("Address");
jsonTextWriter.WriteValue("");
jsonTextWriter.WriteEndObject();

var data = writer.ToString();

Hope that helps.

Jesse Squire
  • 6,107
  • 1
  • 27
  • 30
  • Thanks for your answer. This behavior is correct. I was missing something so this whole question is no longer valid for me. – Tomas Petovsky Nov 15 '16 at 17:16