问题
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"}
回答1:
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);
回答2:
var json = JsonConvert.SerializeObject(new { typ = "photos" }, Formatting.None);
回答3:
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"}
回答4:
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!
回答5:
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" });
来源:https://stackoverflow.com/questions/13917247/generate-json-object-with-newtonsoft-in-a-single-line