json string creation with c#

ⅰ亾dé卋堺 提交于 2021-02-20 02:59:47

问题


I am creating a string variable to use in an rest post call and it is failing. when I debug and look at the json value I am told it is not in json format. It sure seems to be key:value pairs so I an not sure what the issue here is?

instead of double single quotes I also tried escaping the " by using \ like so (neither method is good it seems):

//string postData = "{\"title\":\"Change Title\",  \"description\":\"Create description\",  \"scheduledStartDate\": \"2018-12-24T11:24:48.91Z\",  \"scheduledEndDate'': ''2018-12-25T11:24:48.91Z''  }";

    string postData = @"{''changeNumberForClone'': ''C03688051'',
                        ''scheduledStartDate'': ''2017-12-24T11:24:48.91Z'',
                        ''scheduledEndDate'': ''2017-12-25T11:24:48.91Z''}";        


回答1:


Using NewtonSoft Json.NET, you could use the following code to obtain a correct json string:

Dictionary<String, String> jsonDict = new Dictionary<String, String>();
jsonDict.Add("changeNumberForClone", "C03688051");
jsonDict.Add("scheduledStartDate", "2017-12-24T11:24:48.91Z");
jsonDict.Add("scheduledEndDate", "2017-12-25T11:24:48.91Z");

String postData = JsonConvert.SerializeObject(jsonDict);

If you don't want to add a new library to your project:

String postData = "{\"changeNumberForClone\":\"C03688051\", \"scheduledStartDate\":\"2017-12-24T11:24:48.91Z\", \"scheduledEndDate\": \"2017-12-25T11:24:48.91Z\"}";

In order to produce json strings with multiple levels of depth using the same approach, you can use anonymous objects as follows:

var obj = new { abc = new { def = new { one="1", two="2" } } };
var json = JsonConvert.SerializeObject(obj);

or, if you prefer to use Dictionary instances:

var obj = new Dictionary<String,Object>()
{
    {
        "abc", new Dictionary<String,Object>()
        {
            {
                "def" , new Dictionary<String,Object>()
                {
                    { "one", "1" }, {"two", "2" }
                }
            }
        }
    }
};

the output, for both approaches, would be the following:

{
   "abc": {
      "def" : {
         "one": "1",
         "two": "2",
      },
   }
}


来源:https://stackoverflow.com/questions/47888933/json-string-creation-with-c-sharp

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