Click here to Skip to main content
15,916,692 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi guys!
now, I'm parsing a json file. I have a json file below:
{
"id": 1,
"question": "question1?",
"answer": 2,
"answer_arr": ["ans1","ans2","ans3"]
}

I buil a class:
C#
public class Question
   {
       private int id;

       public int Id
       {
           get { return id; }
           set { id = value; }
       }
       private string quest;

       public string Quest
       {
           get { return quest; }
           set { quest = value; }
       }
       private int answer;

       public int Answer
       {
           get { return answer; }
           set { answer = value; }
       }
       private List<string> answer_arr;

       public List<string> Answer_arr
       {
           get { return answer_arr; }
           set { answer_arr = value; }
       }
   }


I read file below:
C#
var resource = System.Windows.Application.GetResourceStream(new Uri(@"/LuatGiaoThong;component/Data/LuatGT_JSON.txt", UriKind.Relative));
            Stream fs = resource.Stream;
            StreamReader rd = new StreamReader(fs);
            var dict = (JObject)JsonConvert.DeserializeObject(rd.ReadToEnd());

            foreach (var obj in dict["questions"])
            {
                Question ques = new Question()
                {
                    Id = int.Parse(obj["id"].ToString()),
                    Quest = obj["question"].ToString(),
                    Answer_arr = new List<string>(),
                    Answer = int.Parse(obj["answer"].ToString())
                };
                
                JObject answers = (JObject)JsonConvert.DeserializeObject(obj["answer_arr"].ToString());
                MessageBox.Show(answers.ToString());
            }


I dont know how to read "answer_ar" into array?
Anyone can help me? Thanks for your time
Posted

Try something like
C#
JArray answers  = (JArray)JsonConvert.DeserializeObject("answer_arr");
foreach (var item in answers )
{
    foreach(var subitem in item["Answers"])
    {
        //Process subitem
    }
}
 
Share this answer
 
Did you try the class System.Runtime.Serialization.Json.DataContractJsonSerializer:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx[^]?

This is a very powerful approach very good for maintainability of the project as it is agnostic to data model and abstracts out JSON, so you don't have to work with JSON by yourself. Essentially, you just define a data model and mark parts of contract with appropriate .NET attributes. This is explained here:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900