[c#] How to parse my json string in C#(4.0)using Newtonsoft.Json package?

I am new to JSON.In my asp.net application i want to parse the json string.So, i have used Newtonsoft.Json package for reading and writing json data.Now, i can able to parse the simple json data.But now i have received some complex json data for parsing.So, i little bit struck on it.

This is JSON Data:

{
    quizlist: [
     {
            QUIZ: {
                'QPROP': [
                    {
                        'name': 'FB',
                        'intro': '',
                        'timeopen': '1347871440',
                        'timeclose': '1355733840',
                        'timelimit': '0',
                        'noofques': '5',
                        'QUESTION': {
                            'QUEPROP': [
                                {
                                    'questiontext': 'Scienceisbasedont',
                                    'penalty': '0.3333333',
                                    'qtype': 'shortanswer',
                                    'answer': 'cause-and-effect',
                                    'mark'  : '5',
                                    'hint': ''
                                },
                                {
                                    'questiontext': 'otherscientistsevaluateit',
                                    'penalty': '0.3333333',
                                    'qtype': 'shortanswer',
                                    'answer': 'Peerreview',
                                    'mark'  : '5',
                                    'hint': ''
                                },
                                {
                                    'questiontext': 'Watchingavariety',
                                    'penalty': '0.3333333',
                                    'qtype': 'shortanswer',
                                    'answer': 'inductive',
                                    'mark'  : '5',
                                    'hint': ''
                                },
                                {
                                    'questiontext': 'coveriesorideas',
                                    'penalty': '0.3333333',
                                    'qtype': 'shortanswer',
                                    'answer': 'paradigmshift',
                                    'mark'  : '5',
                                    'hint': ''
                                },
                                {
                                    'questiontext': 'proportions',
                                    'penalty': '0.3333333',
                                    'qtype': 'shortanswer',
                                    'answer': 'fixed',
                                    'mark'  : '5',
                                    'hint': ''
                                }
                            ]
                        }
                    }
                ]
            }
        }
     ]
}

This is my C# Code :

dynamic dynObj = JsonConvert.DeserializeObject(jsonString);

            foreach (var data in dynObj.quizlist)
            {
                foreach (var data1 in data.QUIZ.QPROP)
                {
                    Response.Write("Name" + ":" + data1.name + "<br>");
                    Response.Write("Intro" + ":" + data1.intro + "<br>");
                    Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
                    Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
                    Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
                    Response.Write("Noofques" + ":" + data1.noofques + "<br>");
                }
              }

I can able to parse until noofques object in QPROP array objects.Now have to parse data.QUIZ.QPROP.QUESTION.QUEPROP array objects also...

But i failed to parse fully...

Please guide me to get out of this issue...

This question is related to c# json c#-4.0 json.net

The answer is


You could create your own class of type Quiz and then deserialize with strong type:

Example:

quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
                 new JsonSerializerSettings
                 {
                     Error = delegate(object sender1, ErrorEventArgs args1)
                     {
                         errors.Add(args1.ErrorContext.Error.Message);
                         args1.ErrorContext.Handled = true;
                     }
                 });

And you could also apply a schema validation.

http://james.newtonking.com/projects/json/help/index.html


This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

You can use this tool to create appropriate c# classes:

http://jsonclassgenerator.codeplex.com/

and when you will have classes created you can simply convert string to object:

    public static T ParseJsonObject<T>(string json) where T : class, new()
    {
        JObject jobject = JObject.Parse(json);
        return JsonConvert.DeserializeObject<T>(jobject.ToString());
    }

Here that classes: http://ge.tt/2KGtbPT/v/0?c

Just fix namespaces.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to c#-4.0

Xml Parsing in C# EPPlus - Read Excel Table How to add and get Header values in WebApi How to make all controls resize accordingly proportionally when window is maximized? How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project How to get first record in each group using Linq How to get first object out from List<Object> using Linq ASP.Net MVC - Read File from HttpPostedFileBase without save .NET NewtonSoft JSON deserialize map to a different property name Datetime in C# add days

Examples related to json.net

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path Return JsonResult from web api without its properties Checking for empty or null JToken in a JObject Send JSON via POST in C# and Receive the JSON returned? Unexpected character encountered while parsing value JSON.net: how to deserialize without using the default constructor? Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' Convert Json String to C# Object List