5

I need to convert a JsonElement to string but without any carriage return, tabs or spaces. A simple ToString() works but leaves those in:

data.ToString()

Results:

"{\r\n "Field1": "Value1",\r\n "Field2": "Value2"\r\n }"

Looking for:

"{"Field1": "Value1","Field2":"Value2"}"

Sure I could do a simple find and replace string command. However, there will be some fields that will contain carriage return, or tabs or spaces and I don't want to change those.

edit: cannot delete this please someone delete this as it has already been answered.

Xaphann
  • 3,195
  • 10
  • 42
  • 70
  • 1
    Since you don't want to disturb special characters in string literals, your best bet is probably to write your own method that processes the overall JSON string. It'll have to keep track of whether or not it's in a string literal as it traverses the JSON, but that's not hard to do. – Spencer Bench Feb 15 '22 at 18:24
  • 1
    Both of your examples are invalid json and invalid json strings too. Please post the real code if you need the real help. And use Newtonsoft.Json. In this case you will not need any convertation. Text.Json is a garbage and you always need to create an extra code for anything. – Serge Feb 15 '22 at 18:34

1 Answers1

6

In .NET 6 you can use JsonNode.ToJsonString() (using the System.Text.Json.Nodes namespace), but you'd need to convert from the JsonElement to a JsonObject first:

var jsonString = JsonObject.Create(data).ToJsonString();

ToJsonString() takes JsonSerializerOptions as parameter so you could specify WriteIndented if you wanted different behaviour, but by default it will output with WriteIndented = false (which is your desired format).

Could be converted to an extension method:

public static class Extensions
{
    public static string ToJsonString(this JsonElement element, bool indent = false) 
        => element.ValueKind != JsonValueKind.Object
            ? "" 
            : JsonObject.Create(element).ToJsonString(new JsonSerializerOptions { WriteIndented = indent });
}

// usage
// non-indented
var jsonString = element.ToJsonString();
// indented
var jsonString = element.ToJsonString(true);
haldo
  • 14,512
  • 5
  • 46
  • 52