将新项目添加到新列表

时间:2017-06-05 20:37:45

标签: c# json

我希望最终将FAQData作为JSON字符串。首先,我有这个简单的课程:

public class FAQData
{
    public string FAQQuestion { get; set; }
    public string FAQAnswer { get; set; }
}

然后,这就是我不确定如何处理它的地方......

var faqData = JsonConvert.SerializeObject(new List<FAQData>
    {
        {
           FAQQuestion = "Question 1?",
           FAQAnswer = "This is the answer to Question 1."
        },
        {
           FAQQuestion = "Question 2?",
           FAQAnswer = "This is the answer to Question 2."
        },
    })

显然上述语法并不正确。我一直在玩,并尝试各种谷歌搜索,但我似乎无法到达那里。我想要的是FAQData JSON字符串结果如下所示:

[ 
    {"FAQQuestion": "Question 1?", "FAQAnswer": "This is the answer to Question 1."},
    {"FAQQuestion": "Question 2?", "FAQAnswer": "This is the answer to Question 2."}
]

2 个答案:

答案 0 :(得分:2)

您忘记了new FAQData()

JsonConvert.SerializeObject(new List<FAQData>
{
    new FAQData()
    {
        FAQQuestion = "Question 1?",
        FAQAnswer = "This is the answer to Question 1."
    },
    new FAQData()
    {
        FAQQuestion = "Question 2?",
        FAQAnswer = "This is the answer to Question 2."
    },
});

答案 1 :(得分:0)

在序列化为JSON之前,您可以创建一个要操作的变量列表。

            var faqList = new List<FAQData>
            {
                new FAQData()
                {
                   FAQQuestion = "Question 1?",
                   FAQAnswer = "This is the answer to Question 1."
                },
                new FAQData()
                {
                   FAQQuestion = "Question 2?",
                   FAQAnswer = "This is the answer to Question 2."
                },
            };
            faqList.Add(new FAQData()
            {
                FAQQuestion = "Question 3?",
                FAQAnswer = "This is the answer to Question 3."
            });
            var faqData = JsonConvert.SerializeObject(faqList);