2017-09-18 40 views
-3

我是json的新手。 我有一個數組元素的json。我如何遍歷它以顯示網頁中的內容。json反序列化和C#.net

如何顯示json的內容是這樣labl1.text = Questions[0].questionid;

請幫我在這

的Json

{ 
    "dataObj":{ 
     "surveyId":1, 
     "questions":[ 
     { 
      "questionId":7, 
      "questionName":"Picture can help you tell a better story? Snap a photo and share it with us.", 
      "questionType":"IMAGE", 
      "questionSequenceNumber":7, 
      "pageNo":1, 
      "highlightedText":"Snap a photo", 
      "isDynamicText":"N", 
      "answerOptions":[ 
       { 
        "parentQuestion":"5", 
        "parentAnswer":null, 
        "answerOption":null 
       } 
      ] 
     } 
     ] 
    }, 
    "errorCode":0, 
    "errorMessage":"No Error" 
} 
+0

查看[this](http://stackoverflow.com/editing-help)以瞭解如何在SO上使用代碼塊。 –

+1

根據您的json創建類,並使用newtonsoft api將您的json字符串反序列化到這些新創建的類中。其簡單和簡單的方法。 –

+0

@l_raffa,JPBlanc,Sachila Ranawaka,Jakob Christensen,greg-449轉到所有標記爲重複的人,請您提供原始鏈接。它不應該是通常的json反序列化,我已經要求對數組元素進行反序列化。請提供原始問題的鏈接。 –

回答

0

首先,您可以定義以下類:

public class AnswerOption 
{ 

    [JsonProperty("parentQuestion")] 
    public string ParentQuestion { get; set; } 

    [JsonProperty("parentAnswer")] 
    public object ParentAnswer { get; set; } 

    [JsonProperty("answerOption")] 
    public object Option { get; set; } 
} 

public class Question 
{ 

    [JsonProperty("questionId")] 
    public int QuestionId { get; set; } 

    [JsonProperty("questionName")] 
    public string QuestionName { get; set; } 

    [JsonProperty("questionType")] 
    public string QuestionType { get; set; } 

    [JsonProperty("questionSequenceNumber")] 
    public int QuestionSequenceNumber { get; set; } 

    [JsonProperty("pageNo")] 
    public int PageNo { get; set; } 

    [JsonProperty("highlightedText")] 
    public string HighlightedText { get; set; } 

    [JsonProperty("isDynamicText")] 
    public string IsDynamicText { get; set; } 

    [JsonProperty("answerOptions")] 
    public IList<AnswerOption> AnswerOptions { get; set; } 
} 

public class DataObj 
{ 

    [JsonProperty("surveyId")] 
    public int SurveyId { get; set; } 

    [JsonProperty("questions")] 
    public IList<Question> Questions { get; set; } 
} 

public class Example 
{ 
    [JsonProperty("dataObj")] 
    public DataObj DataObj { get; set; } 

    [JsonProperty("errorCode")] 
    public int ErrorCode { get; set; } 

    [JsonProperty("errorMessage")] 
    public string ErrorMessage { get; set; } 
} 

然後,你可以反序列化您的JSON如下:

var example = JsonConvert.DeserializeObject<Example>(json); 

其中json是保存要反序列化JSON的一個變量。

最後,你可以訪問首創質疑如下ID:

labl1.text = example.DataObj?.Questions?.FirstOrDefault()?.QuestionId; 
+0

謝謝,我已經做了,忘了在問題中加入它。 –

+0

@ tony.g不用客氣。請檢查我的upadte。 – Christos

+0

問題是在創建類後,我仍然無法反序列化數組值。任何用於解析數組元素的代碼片段示例。 –

0

使用該網站,以幫助您生成JSON字符串C#類http://json2csharp.com/

注意:不要忘記將數據類型double 。