I have a dictionary of FormCollection named values and I want to add a FormNumber that is only a string to it like the response below:
Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);
string FormNumber="6";
CodePudding user response:
You would need a model class as a dictionary is limited to the Key and Value properties.
public class Model {
public Model(int num, Dictionary<string, string> values)
{
FormNumber = num;
Values = values;
}
public int FormNumber { get; set; }
public Dictionary<string, string> Values {get; set;}
}
string FormNumber = "6"
Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);
// convert to int as your JSON format is int
int number = int.Parse(FormNumber);
Model model = new Model(number, Values);
string json = JsonSerializer.Serialize(model);
CodePudding user response:
try this
var FormNumber = "6";
var ValuesList = Values.Select(c => new KeyValuePair<string,string>(c.Key,c.Value) ).ToArray();
var model = new { FormNum = FormNumber, Values = ValuesList};
return model;
//or I would not recomend
var json= JsonConvert.SerializeObject(model, Newtonsoft.Json.Formatting.Indented);
return json