How to parse my json string in C#(4.0)using Newtonsoft.Json package?
Asked Answered
I

5

34

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...

Impecunious answered 12/12, 2012 at 12:32 Comment(0)
D
16
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>");

        foreach (var queprop in data1.QUESTION.QUEPROP)
        {
            Response.Write("Questiontext" + ":" + queprop.questiontext  + "<br>");
            Response.Write("Mark" + ":" + queprop.mark  + "<br>");
        }
    }
}
Dissepiment answered 12/12, 2012 at 12:42 Comment(0)
I
15

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.

Insurgent answered 12/12, 2012 at 12:35 Comment(6)
:Thanks.It created some .cs files.How do i use it in my application.I want to store that information into my DB.for example,my json string contains arrays then i want to store it in C# array and then copy to my Database...Impecunious
ok, just add that cs files to your project and fix namespaces. Next, when you will have raw json string you can convert it to object by calling SampleResponse1 obj = ParseJsonObject<SampleResponse1>(jsonStr); Note! SamplemResponse1 is root class genereated by that tool, if you clicked Generate without setting another name. Probably you will want to change itInsurgent
:then how do i store all the details parsed from json string into C# data structure...Impecunious
ParseJsonObject will return c# class to you. So if e.g. root class generated by that tool called RootJson. RootJson obj = ParseJsonObject<RootJson >(jsonStr); next to access all quizez simply use foreach(Quiz quiz in obj.Quizlist ) {//here you can read all properties of current quiz}. Next you can store these properties in databaseInsurgent
:Now i understood...Thanks for your efforts...But now i want to read it from each http request.I have 4 different json data.So, i have to create C# code for those data early and then do your process according to the web request right... tell me am i wrong or right?Impecunious
yes, if you have different structure of json strings you need to create classes for those strings and after you will have it you will be able to convert string representation to c# object like described above. CheersInsurgent
C
5

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

Crippen answered 12/12, 2012 at 13:35 Comment(0)
W
3

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);
        }
    }
}
Ware answered 24/6, 2015 at 13:24 Comment(0)
N
0

First of all good approach will be to convert JSON string to model using this site https://www.site24x7.com/tools/json-to-csharp.html

than use your model try {
client.BaseAddress = new Uri("http://api.weatherapi.com"); var response = await client.GetAsync($"/v1/current.json?key=(YOUR API KEY)&q={city}&aqi=no"); response.EnsureSuccessStatusCode();

var stringResult = await response.Content.ReadAsStringAsync();
var rawWeather = JsonConvert.DeserializeObject<OpenWeatherResponse>(stringResult);

return Ok(new
{
    City= rawWeather?.location.name,
    Temp = rawWeather?.current.temp_c,
    Wind= rawWeather?.current.wind_kph,
    Date= rawWeather?.current.last_updated,
    Condition= rawWeather?.current.condition.text,
    Conditionico = rawWeather?.current.condition.icon
});

} catch (HttpRequestException httpRequestException) { return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}"); }

Nicks answered 16/1 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.