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.
In .NET 6 you can use
JsonNode.ToJsonString()(using the System.Text.Json.Nodes namespace), but you'd need to convert from theJsonElementto aJsonObjectfirst:ToJsonString()takesJsonSerializerOptionsas parameter so you could specifyWriteIndentedif you wanted different behaviour, but by default it will output withWriteIndented = false(which is your desired format).Could be converted to an extension method: