1

I have a Json data please suggest me how to read this type of 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"
         }
         ]}
   ]}
FeliceM
  • 4,163
  • 9
  • 48
  • 75
Jatinder Sharma
  • 277
  • 1
  • 3
  • 14

3 Answers3

1

Newtonsoft.Json is my favorite library to manipulate JSON

Your code should be something like:

EDITED

    public class AnswerObj{

       public string Answer{get;set;}

    }

    public class QuestionObj{

       public string Question {get;set;}

       public int CorrectAnswer {get;set;}

       public List<AnswerObj> Answers {get;set;}
    }

    public class QuestionsRepository
    {
       public List<QuestionObj> Questions {get;set;}
    }

    //Here is the code for reading your JSON
    string json = "Your_JSON_COMES_HERE as a string"

    QuestionsRepository questions = JsonConvert.DeserializeObject<QuestionsRepository>(json);
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
  • i tried as you modify the class name for question and answer to QuestionObj and AnswerObj but still geting error – Jatinder Sharma Dec 26 '13 at 06:12
  • What error do you get? Are you using Newtonsoft.Json library? – Alex Art. Dec 26 '13 at 06:17
  • http://stackoverflow.com/questions/12402085/how-to-parse-json-object-in-c – Jatinder Sharma Dec 26 '13 at 06:19
  • Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TestSidebar.QuestionObj]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. – Jatinder Sharma Dec 26 '13 at 07:28
  • Path 'Questions', line 2, position 14. and last line of error – Jatinder Sharma Dec 26 '13 at 07:31
  • and code is here string filePath = Server.MapPath("App_Data/history.txt"); using (StreamReader r = new StreamReader(filePath)) { string json = r.ReadToEnd(); List questions = JsonConvert.DeserializeObject>(json); } – Jatinder Sharma Dec 26 '13 at 07:31
  • I see where the problem is - the input is not a list of question objects it is a questions object that contains a collection of questions. Please see the edited answer. Hopefully it is going to work! – Alex Art. Dec 26 '13 at 07:39
  • Hey Alex Art. i try your edited Answer but same error again string filePath = Server.MapPath("App_Data/history.txt"); using (StreamReader r = new StreamReader(filePath)) { string json = r.ReadToEnd(); List questions = JsonConvert.DeserializeObject>(json); } } – Jatinder Sharma Dec 26 '13 at 07:44
  • You didn't type it correctly it's not a List questions = JsonConvert.DeserializeObject>(json); it's a QuestionsRepository questions = JsonConvert.DeserializeObject(json); – Alex Art. Dec 26 '13 at 07:47
  • I prefer not to rely on frameworks, when it is not needed, so your answer uses some havy extra code, where it is not really needed anyway – Alan Turing Dec 26 '13 at 14:36
1

You can use builtin .NET, DataContractJsonSerializer class, which can be used to Serialize and Deserialize json strings. (MSDN Link)

Here is a complete tutorial in MSDN: (How to: Serialize and Deserialize JSON data)

Arin Ghazarian
  • 5,105
  • 3
  • 23
  • 21
0

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

Alan Turing
  • 2,482
  • 17
  • 20