2017-06-05 73 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); 
相關問題