Reputation: 11592
I have some data that are stored in the C# Dictionary.Now i want to serialize this dictionary objects to json format that i specified below...
This is my C# Code:
public void generateJsonString()
{
StudInfo studDetails = new StudInfo();
studDetails.GetQuestions.Add("s1", "Q1,Q2");
studDetails.GetQuestions.Add("s2", "Q1,Q3");
studDetails.GetQuestions.Add("s3", "Q4,Q5");
string jsonString = JsonConvert.SerializeObject(studDetails, Formatting.Indented);
}
public class StudInfo
{
public Dictionary<string, string> GetQuestions = new Dictionary<string, string>();
}
It was given the output like below...
{
"GetQuestions": {
"s1": "Q1,Q2",
"s2": "Q1,Q3",
"s3": "Q4,Q5"
}
}
But my required format is :
{
GetQuestions:[
{
"s1":"Q1,Q2",
"s2":"Q3,Q4",
"s3":"Q5,Q6",
}]
}
Needed update in the generated output is...(with respect to my required format)
Upvotes: 0
Views: 1078
Reputation: 348
string serializedString = JsonConvert.SerializeObject(studDetails);
Deserialize (If needed)
StudInfo = JsonConvert.Deserialize<StudInfo>(serializedString);
This will convert it back to a StudInfo object using generics and runtime safety.
Changing
Public Dictionary<string, string>
to public List<Dictionary<string, string>>
will force it into an array once serialized.
Upvotes: 4