How to avoid the tailing space space after ":" in using Newtonsoft

Viewed 471

After writing the JSON into the file using

File.WriteAllText(fileName, JsonConvert.SerializeObject(jsonToWrite, Formatting.Indented)). 

I am getting a tailing space after every ":". How to avoid it?

Current in red, expected in Green enter image description here

2 Answers

The code that adds the space is located in JsonTextWriter.WriteIndentSpace, and is called by the standard JsonWriter.

One possible option is to write your own JsonTextWriter derived class, override WriteIndentSpace and do nothing in it.

class MyWriter : JsonTextWriter
{
    public MyWriter(TextWriter sw) : base(sw)
    { }

    protected override void WriteIndentSpace()
    { }
}

You then need to write custom serialization code to actually use this writer

    static string Convert(object value, JsonSerializerSettings settings)
    {
        JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
        StringBuilder sb = new StringBuilder(256);
        StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
        using (var jsonWriter = new MyWriter(sw))
        {
            jsonWriter.Formatting = jsonSerializer.Formatting;

            jsonSerializer.Serialize(jsonWriter, value, null);
        }

        return sw.ToString();
    }

You can then call it with whatever settings you want, and an IndentSpace will never be inserted.

var json = Convert(myObject, new JsonSerializerSettings{ Formatting = Formatting.Indented });

Some of the code could be simplified if you know exactly what settings you want to use every time.

dotnetfiddle

Replace ": " by ":" in json content with string.Replace

string fileName = "file.txt";
string jsonFromSerialization = "{\n\t\"foo\": \"bar\",\n\t\"bar\": \"foo\"\n}"; //JsonConvert.SerializeObject
jsonFromSerialization = jsonFromSerialization.Replace("\": \"", "\":\"");
File.WriteAllText(fileName, jsonFromSerialization);

Replace "<any number of whitespaces>:<any number of whitespaces>"
eg. " : " by ":" in json content with Regex.Replace

string fileName = "file.txt";
string jsonFromSerialization = "{\n\t\"foo\"     :     \"bar\",\n\t\"bar\"    :  \"foo\"\n}"; //JsonConvert.SerializeObject
string pattern = "\"\\s*:\\s*\"";
jsonFromSerialization = Regex.Replace(jsonFromSerialization, pattern, "\":\"");
File.WriteAllText(fileName, jsonFromSerialization);

Result
file


Another approach. Thanks to Jon Skeet for his suggestion. In this example validates special strings in the value of a key.

eg.

{"foo":   "xyz\": ","bar"    :  "foo"}

Code

string JsonReplace(string json)
{
    string pattern = @"(\s*""\w+"")\s*:\s*";
    foreach (Match m in Regex.Matches(json, pattern))
    {
        json = json.Replace(m.Value, m.Value.Replace(" ", string.Empty));
    }
    return json;
}

string fileName = "file.txt";
var data = new
{
    foo = "xyz\": ",
    bar = "foo"
};
string jsonFromSerialization = JsonConvert.SerializeObject(data);
jsonFromSerialization = JsonReplace(jsonFromSerialization);
File.WriteAllText(fileName, jsonFromSerialization);

Result
result

Related