Question

I'm using the Json.NET (Newtonsoft.Json) package in a Portable Class Library (PCL) project (targetting Xamarin.Android and Xamarin.iOS) and would like to get a string representation of a JSON object with no formatting (i.e. no new lines, no tabs etc). How can I do this?

Currently, if I call JObject.ToString() on a JObject instance, I get a string with the new line (\n) character as follows:

"{\n  \"key\": \"value\"\n}"

Essentially, what I'd like to do is parse an initial string representation of a JSON object which or may not contain formatting/indentation/etc, convert the parsed JSON object to a string which does not contain formatting/indentation/etc, and end with a string something as follows:

"{\"key\":\"value\"}"

Is this possible with the Json.NET (Newtonsoft.Json) package in a PCL project? Is there another library I could use to accomplish this?

Was it helpful?

Solution

Have you tried the overload of JObject.ToString() which accepts a Formatting enum value?

string json = jObject.ToString(Formatting.None);

OTHER TIPS

Hmm, I can't find a way to do this with JObject but looks it is possible with JsonConvert, as follows:

string json = "{\n\t\"key\":\"value\"\n}"
var parsedJSon = JsonConvert.DeserializeObject (json);
string jsonNoFormatting = JsonConvert.SerializeObject (parsedJSon, Formatting.None);

I wonder if there's a better way to do this?...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top