用C#创建json字符串 [英] json string creation with c#
问题描述
我正在创建一个字符串变量,用于在调用后的调用中,但是失败了.当我调试并查看json值时,我被告知它不是json格式.肯定是关键:值对,所以我不确定这里的问题是什么?
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''}";
推荐答案
使用 NewtonSoft Json.NET ,您可以使用以下代码获取正确的json
字符串:
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\"}";
为了使用相同的方法生成具有多个深度级别的json
字符串,可以按以下方式使用anonymous objects
:
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);
,或者,如果您更喜欢使用Dictionary
实例:
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" }
}
}
}
}
};
两种方法的输出如下:
{
"abc": {
"def" : {
"one": "1",
"two": "2",
},
}
}
这篇关于用C#创建json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!