C# 在一行中使用 NewtonSoft 生成 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13917247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate JSON object with NewtonSoft in a single line
提问by Calimero
I'm using the JSON library NewtonSoftto generate a JSON string:
我正在使用 JSON 库NewtonSoft生成一个 JSON 字符串:
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"}
回答by L.B
var json = JsonConvert.SerializeObject(new { typ = "photos" }, Formatting.None);
回答by Quispie
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 thison Json.Net:
编辑:搜索后我在 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 thiswebsite.
也许你可以使用这个网站上的信息。
But I'm not sure, if the output will be on one line... Good luck!
但我不确定,如果输出将在一行上......祝你好运!
回答by tpeczek
You can use the overload of JObject.ToString()which takes Formattingas parameter:
您可以使用的过载JObject.ToString()这需要Formatting作为参数:
JObject obj = JObject.FromObject(new
{
typ = "photos"
});
return obj.ToString(Formatting.None);
回答by Anup Sharma
If someone here who doesn't want to use any external library in MVC, they can use the inbuilt System.Web.Script.Serialization.JavaScriptSerializer
如果这里有人不想在 MVC 中使用任何外部库,他们可以使用内置的 System.Web.Script.Serialization.JavaScriptSerializer
One liner for that will be:
一个班轮将是:
var JsonString = new JavaScriptSerializer().Serialize(new { typ = "photos" });
回答by DLeh
Here's a one-liner to minify JSON that you only have a string for:
这是一个用于缩小 JSON 的单行代码,您只有一个字符串:
var myJson = "{\"type\" :\"photos\" }";
JObject.Parse(myJson).ToString(Newtonsoft.Json.Formatting.None)
Output:
输出:
{"type":"photos"}

