Generate JSON object with NewtonSoft in a single line

后端 未结 5 2032
自闭症患者
自闭症患者 2020-12-04 20:49

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

JObject out = JObject.FromObject(new
            {
                typ = \"photos\"
                


        
相关标签:
5条回答
  • 2020-12-04 21:32

    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"}
    
    0 讨论(0)
  • 2020-12-04 21:32

    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!

    0 讨论(0)
  • 2020-12-04 21:41

    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);
    
    0 讨论(0)
  • 2020-12-04 21:51
    var json = JsonConvert.SerializeObject(new { typ = "photos" }, Formatting.None);
    
    0 讨论(0)
  • 2020-12-04 21:52

    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" });
    
    0 讨论(0)
提交回复
热议问题