'Remove all non-essential json formatting in C#

Let's say I have some convoluted json like so:

{
  "ref": "some",
  "repository": {
    "id": 123456789,
    "name": "foo bar"
  }
}

I'm trying to get it into this format:

{"ref":"some","repository":{"id":123456789,"name":"foo bar"}}

So, no whitespace or newlines except the ones in the json key/value pairs themselves.

Regex.Replace(myJson, @"\s+", string.Empty) removes the spaces from foo bar resulting in foobar.

Using

JsonConvert.SerializeObject(myJson, Formatting.None)

Gives me

{\n \"ref\": \"some\",\n \"repository\": {\n \"id\": 123456789,\n \"name\": \"foo bar\"\n }\n}

What's another way I can remove all non-essential white spaces and newlines on this json?



Solution 1:[1]

You can always deserialize your json into an object then reserialize it. Without providing any options, the default result is in line with what you're looking for.

    var rawJson = @"{
  ""ref"": ""some"",
  ""repository"": {
    ""id"": 123456789,
    ""name"": ""foo bar""
  }
}";
    var tempObj = JsonConvert.DeserializeObject(rawJson);
    var inlineJson = JsonConvert.SerializeObject(tempObj);

The output of that is {"ref":"some","repository":{"id":123456789,"name":"foo bar"}}

Solution 2:[2]

JToken.FromObject(yourObject).ToString(Formatting.None);

This removes all new lines and white space outside of property values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gilliduck
Solution 2