programing

Newtonsoft를 사용하여 C#(4.0)의 json 문자열을 해석하는 방법Json 패키지?

telebox 2023. 3. 18. 08:27
반응형

Newtonsoft를 사용하여 C#(4.0)의 json 문자열을 해석하는 방법Json 패키지?

JSON은 처음입니다.asp.net 어플리케이션에서 json 문자열을 해석하고 싶습니다.그래서 나는 뉴턴소프트를 사용해봤다.Json 데이터를 읽고 쓰기 위한 Json 패키지입니다.이제 간단한 json 데이터를 해석할 수 있습니다.하지만 지금은 파싱을 위해 복잡한 json 데이터를 받았습니다.그래서 조금 떠올랐어요.

JSON 데이터:

{
    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': ''
                                }
                            ]
                        }
                    }
                ]
            }
        }
     ]
}

이것은 C# 코드입니다.

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>");
                }
              }

QPROP 어레이 오브젝트의 noofques 오브젝트까지 해석할 수 있습니다.이제 데이터를 해석해야 합니다.QUISS.QPROP질문.QUEPROP 배열 개체도...

하지만 난 완전히 해석하는 데 실패했어

이 문제에서 벗어날 수 있도록 안내해주세요...

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>");
        }
    }
}

이 도구를 사용하여 적절한 c# 클래스를 만들 수 있습니다.

http://jsonclassgenerator.codeplex.com/

클래스를 만들 때 문자열을 개체로 간단하게 변환할 수 있습니다.

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

다음 클래스는 http://ge.tt/2KGtbPT/v/0?c 입니다.

네임스페이스만 고치면 돼

자체 유형 퀴즈 클래스를 만든 다음 강력한 유형으로 역직렬화할 수 있습니다.

예:

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

스키마 검증을 적용할 수도 있습니다.

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

이것은 구글 맵 API를 예로 들어 JSON 파싱의 간단한 예입니다.지정된 우편번호의 도시 이름이 반환됩니다.

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);
        }
    }
}

언급URL : https://stackoverflow.com/questions/13839865/how-to-parse-my-json-string-in-c4-0using-newtonsoft-json-package

반응형