简体   繁体   中英

JSON Serialize array returns NULL in JSON string

I am building a JSON model like this

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

below code for serialization

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

But when i try to build this from a dynamic list of values like

   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
   }

I got the JSON as

   "labels": [
  [
    null,
    null
  ]
]

But i am expecting this json as

"labels" : { "import", "automation"}

How can i make the array serialization right way

I modified your code in a console Application.

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);

The result is as follows:
在此处输入图片说明

Hope it answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM