I prefer to use at least frameworks as possible. Look at my code.
For the given object structure:
public class QuestionsRepository
{
public List<QuestionObj> Questions;
}
public class QuestionObj
{
public string Question;
public UInt16 CorrectAnswer;
public AnswerObj[] Answers;
}
public class AnswerObj
{
public string Answer;
}
Declare trivial simplest wrapper:
public static class JsonUtils
{
class JsonSerializer<T>
{
static DataContractJsonSerializer xs = new DataContractJsonSerializer(typeof(T));
public static object DeserializeObject(string serializedData, Encoding encoding)
{
byte[] data = encoding.GetBytes(serializedData);
MemoryStream sr = new MemoryStream(data);
return xs.ReadObject(sr);
}
public static string SerializeObject(T obj, Encoding encoding)
{
MemoryStream ms = new MemoryStream();
xs.WriteObject(ms, obj);
byte[] data = ms.ToArray();
return encoding.GetString(data);
}
}
public static T DeserializeObject<T>(this string serializedData)
{
return (T)JsonSerializer<T>.DeserializeObject(serializedData, Encoding.Default);
}
public static string SerializeObject<T>(this T obj)
{
return JsonSerializer<T>.SerializeObject(obj, Encoding.Default);
}
}
Sample:
class Program
{
static void Main()
{
try
{
string json = "{\"Questions\": [{ \"Question\": \"Who was the Chola King who brought Ganga from North to South?\", \"CorrectAnswer\": 1, \"Answers\": [ { \"Answer\": \"Raja Raja Chola\" }, { \"Answer\": \"Rajendra Chola\" }, { \"Answer\": \"Parantaka\" }, { \"Answer\": \"Mahendra\" } ] }, { \"Question\": \"The writ of 'Habeas Corpus' is issued in the event of:\", \"CorrectAnswer\": 2 , \"Answers\": [{ \"Answer\": \"Loss of Property\" }, { \"Answer\": \"Refund of Excess Taxes\" }, { \"Answer\": \"Wrongful Police Detention\" }, { \"Answer\": \"Violation of the Freedom of Speech\" }] }]}}";
QuestionsRepository newRepository = json.DeserializeObject<QuestionsRepository>();
for (int i = 0; i < newRepository.Questions.Count; i++)
{
Console.WriteLine("{0}", newRepository.Questions[i].Question);
int count = 1;
foreach (var answer in newRepository.Questions[i].Answers)
{
Console.WriteLine("\t{0}) {1} ({2})", count, answer.Answer, newRepository.Questions[i].CorrectAnswer == count ? "+" : "-");
count++;
}
}
}
catch (SerializationException serEx)
{
Console.WriteLine(serEx.Message);
Console.WriteLine(serEx.StackTrace);
}
}
}
P.S.: Classes must be top-level enities with default constructor available (visible, accessible classes for data serializer) to be uses in DataContractJsonSerializer