Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# JsonElement to string without formatting

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 }"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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 jsonObject = JsonObject.Create(data);
Console.WriteLine(jsonObject.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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading