Generate JSON object with NewtonSoft in a single line

梦想的初衷 提交于 2019-12-17 15:34:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!