1

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

4
  • you migth want to first build a model class to represent your json object in c#. This way you can define a property of name labels and save a List<string> or a string[] in there. Have a look at this quicktype example i through together Commented May 23, 2018 at 5:29
  • I have some restrictions of using model class approach . since i have lot of properties and it is varying for each request. So i prefer on the go or t dynamic model creation Commented May 23, 2018 at 5:33
  • 1
    What is jira_labels? Commented May 23, 2018 at 5:40
  • 1
    Am I guessing right that you want to have lp_list inside the labels property at the end? If yes why are your asigning jira_labels to it? Commented May 23, 2018 at 5:42

1 Answer 1

4

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:
enter image description here

Hope it answers your question.

Sign up to request clarification or add additional context in comments.

5 Comments

The lp_list.ToArray() isn't necessary in this case.
Yeah,I modify code like this " labels = lp_list",it also take effective.
Thanks oh and +1 for finishing basically 2 seconds before me with the answer
my pleasure :).
This is the code i used and its my mistake of assigning items to list string . Now i figured it out an thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.