简体   繁体   中英

How to serialize my data that are stored in C# dictionary into json object by using C# and json.net?

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)

  1. I don't need double quote for GetQuestions
  2. I want to create getQuestions as array object
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.

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