c# - JSON 序列化数组在 JSON 字符串中返回 NULL

标签 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"}

如何正确地序列化数组

最佳答案

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

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

希望它能回答您的问题。

关于c# - JSON 序列化数组在 JSON 字符串中返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480380/

相关文章:

c# - ASP.NET MVC View 模型问题

asp.net - 网络 API : The requested resource does not support http method 'GET'

android - 带有条件的 JSON 文件的自动完成列表

c# - 使用 Newtonsoft 反序列化 JSON 对象 C#

c# - ISO 语法是否遵循特定格式

c# - 如何在联系我们页面中发送带有用户电子邮件的电子邮件?

wcf - 数据合约中未设置数据成员字段时如何不返回 null

c# - 填充现有对象时在添加项目之前清除集合

asp.net-mvc - MVC Web API 出现错误: 'ObjectContent` 1' 类型无法序列化响应正文,构造函数的参数数量不正确

c# - 动态创建的单选按钮不会在单击时执行事件