How to create JSON string in C#

后端 未结 14 1040
闹比i
闹比i 2020-11-22 12:39

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the

14条回答
  •  心在旅途
    2020-11-22 13:26

    Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.

            //Create my object
            var my_jsondata = new
            {
                Host = @"sftp.myhost.gr",
                UserName = "my_username",
                Password = "my_password",
                SourceDir = "/export/zip/mypath/",
                FileName = "my_file.zip"
            };
    
            //Tranform it to Json object
            string json_data = JsonConvert.SerializeObject(my_jsondata);
    
            //Print the Json object
            Console.WriteLine(json_data);
    
            //Parse the json object
            JObject json_object = JObject.Parse(json_data);
    
            //Print the parsed Json object
            Console.WriteLine((string)json_object["Host"]);
            Console.WriteLine((string)json_object["UserName"]);
            Console.WriteLine((string)json_object["Password"]);
            Console.WriteLine((string)json_object["SourceDir"]);
            Console.WriteLine((string)json_object["FileName"]);
    

提交回复
热议问题