JSON Serialize数组在JSON字符串中返回NULL

时间:2018-05-23 05:22:56

标签: c# json json.net

我正在构建像这样的JSON模型

JObject issue_model = JObject.FromObject(new
{
   labels = new[] { "import", "automation"}
}

下面的序列化代码

string request_json = JsonConvert.SerializeObject(issue_model,
                  Newtonsoft.Json.Formatting.Indented,
                  new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); 

但是当我尝试从像

这样的动态值列表中构建它时
   list<string> lp_list = new list<string>();
   //lp_list contains a list of string values
   string[] lp_labels = lp_list.ToArray();
   JObject issue_model = JObject.FromObject(new
   {
      labels = jira_labels
   }

我把JSON作为

   "labels": [
  [
    null,
    null
  ]
]

但我期待这个json为

  

“labels”:{“import”,“automation”}

如何使数组序列化正确

1 个答案:

答案 0 :(得分:4)

我在控制台应用程序中修改了你的代码。

List<string> lp_list = new List<string>();
lp_list.Add("import");
lp_list.Add("automation");

//lp_list contains a list of string values
//string[] lp_labels = lp_list.ToArray();
JObject issue_model = JObject.FromObject(new
{
    labels = lp_list
});

Console.WriteLine(issue_model);

结果如下:
enter image description here

希望它能回答你的问题。

相关问题