2017-06-05 70 views
0

我想在这里结束与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."} 
] 
+0

你的意思是你想要的输出为 [ { “FAQQuestion”: “问题1?”, “FAQAnswer”: “这是对问题1回答”},{ “FAQQuestion” :“问题2?”,“FAQAnswer”:“这是问题2的答案。”} ] – Vinod

+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." 
    }, 
}); 
+0

谢谢!现在测试! –

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); 
相关问题