Generate JSON object with NewtonSoft in a single line

C#Jsonjson.net

C# Problem Overview


I'm using the JSON library NewtonSoft to generate a JSON string:

JObject out = JObject.FromObject(new
            {
                typ = "photos"
            });

            return out.ToString();

Output:

{
  "typ": "photos"
}

My question: Is it possible to get the output in a single line like:

{"typ": "photos"}

C# Solutions


Solution 1 - C#

You can use the overload of JObject.ToString() which takes Formatting as parameter:

JObject obj = JObject.FromObject(new
{
    typ = "photos"
});

return obj.ToString(Formatting.None);

Solution 2 - C#

var json = JsonConvert.SerializeObject(new { typ = "photos" }, Formatting.None);

Solution 3 - C#

Here's a one-liner to minify JSON that you only have a string for:

var myJson = "{\"type\"    :\"photos\"               }";
JObject.Parse(myJson).ToString(Newtonsoft.Json.Formatting.None)

Output:

{"type":"photos"}

Solution 4 - C#

I'm not sure if this is what you mean, but what I do is this::

string postData = "{\"typ\":\"photos\"}";

EDIT: After searching I found this on Json.Net:

string json = @"{
  CPU: 'Intel',
  Drives: [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}";

JObject o = JObject.Parse(json);

and maybe you could use the info on this website.

But I'm not sure, if the output will be on one line... Good luck!

Solution 5 - C#

If someone here who doesn't want to use any external library in MVC, they can use the inbuilt System.Web.Script.Serialization.JavaScriptSerializer

One liner for that will be:

var JsonString = new JavaScriptSerializer().Serialize(new { typ = "photos" });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCalimeroView Question on Stackoverflow
Solution 1 - C#tpeczekView Answer on Stackoverflow
Solution 2 - C#L.BView Answer on Stackoverflow
Solution 3 - C#DLehView Answer on Stackoverflow
Solution 4 - C#QuispieView Answer on Stackoverflow
Solution 5 - C#Anup SharmaView Answer on Stackoverflow