Как мне разобрать JSON в c#? - PullRequest
0 голосов
/ 16 апреля 2020

Когда-то go я отправил вопрос о разборе JSON, и я получил действительно хороший ответ. Мой json пока:

{
  "stepLang": "en",
  "isFromCache": false,
  "isInNotebook": false,
  "standardQuery": "(-\\log_{2}(\\sqrt{2}))^{2}",
  "relatedProblems": [],
  "subject": "Algebra",
  "topic": "Algebra",
  "subTopic": "Simplify",
  "solutions": [
    {
      "step_input": "(-\\log_{2}(\\sqrt{2}))^{2}",
      "entire_result": "=\\frac{1}{4}",
      "solvingClass": "Solver",
      "isInterimStep": true,
      "isOpen": false,
      "isShowSolutionAfterStep": true,
      "title": {
        "text": {
          "createdText": "(-\\log_{2}(\\sqrt{2}))^{2}=\\frac{1}{4}\\quad(\\mathrm{Decimal:{\\quad}} 0.25)"
        }
      },
      "steps": [
        {
          "step_input": "\\log_{2}(\\sqrt{2})",
          "entire_result": "=(-\\frac{1}{2})^{2}",
          "isInterimStep": true,
          "isOpen": false,
          "isShowSolutionAfterStep": true,
          "title": {
            "text": {
              "createdText": "\\mathrm{Simplify} \\log_{2}(\\sqrt{2}):{\\quad}\\frac{1}{2}"
            }
          },
          "steps": [
            {
              "entire_result": "=\\log_{2}(2^{\\frac{1}{2}})",
              "isInterimStep": false,
              "isOpen": false,
              "isShowSolutionAfterStep": false,
              "explanation": [
                {
                  "createdText": "\\mathrm{Rewrite as}"
                }
              ]
            },
            {
              "entire_result": "=\\frac{1}{2}\\log_{2}(2)",
              "isInterimStep": false,
              "isOpen": false,
              "isShowSolutionAfterStep": false,
              "title": {
                "text": {
                  "createdText": "\\mathrm{Apply log rule }\\log_{a}(x^b)=b\\cdot\\log_{a}(x),\\quad\\mathrm{ assuming }x \\geq 0"
                }
              }
            },
            {
              "entire_result": "=\\frac{1}{2}",
              "isInterimStep": false,
              "isOpen": false,
              "isShowSolutionAfterStep": false,
              "title": {
                "text": {
                  "createdText": "\\mathrm{Apply log rule}"
                }
              },
              "general_rule": {
                "text": {
                  "createdText": "\\log_a(a)=1"
                }
              },
              "practiceLink": "/practice/logarithms-practice",
              "practiceTopic": "Expand FOIL"
            }
          ]
        },
        {
          "step_input": "(-\\frac{1}{2})^{2}",
          "isInterimStep": true,
          "isOpen": false,
          "isShowSolutionAfterStep": true,
          "title": {
            "text": {
              "createdText": "\\mathrm{Simplify}"
            }
          },
          "steps": [
            {
              "entire_result": "=(\\frac{1}{2})^{2}",
              "isInterimStep": false,
              "isOpen": false,
              "isShowSolutionAfterStep": false,
              "title": {
                "text": {
                  "createdText": "\\mathrm{Apply exponent rule}"
                }
              },
              "general_rule": {
                "text": {
                  "createdText": "(-a)^{n}=a^{n}, \\mathrm{if }n\\mathrm{ is even}"
                }
              },
              "explanation": [
                {
                  "createdText": "(-\\frac{1}{2})^{2}=(\\frac{1}{2})^{2}"
                }
              ]
            },
            {
              "entire_result": "=\\frac{1^{2}}{2^{2}}",
              "isInterimStep": false,
              "isOpen": false,
              "isShowSolutionAfterStep": false,
              "title": {
                "text": {
                  "createdText": "\\mathrm{Apply exponent rule}"
                }
              },
              "general_rule": {
                "text": {
                  "createdText": "(\\frac{a}{b})^{c}=\\frac{a^{c}}{b^{c}}"
                }
              },
              "practiceLink": "/practice/exponent-practice",
              "practiceTopic": "Expand FOIL"
            },
            {
              "entire_result": "=\\frac{1}{2^{2}}",
              "isInterimStep": false,
              "isOpen": false,
              "isShowSolutionAfterStep": false,
              "explanation": [
                {
                  "createdText": "\\mathrm{Apply rule} 1^{a}=1"
                },
                {
                  "createdText": "1^{2}=1"
                }
              ]
            },
            {
              "entire_result": "=\\frac{1}{4}",
              "isInterimStep": false,
              "isOpen": false,
              "isShowSolutionAfterStep": false,
              "explanation": [
                {
                  "createdText": "2^{2}=4"
                }
              ]
            }
          ]
        }
      ]
    }
  ],
  "dym": {
    "inputEquation": "\\left(-\\log _{2} \\sqrt{2}\\right)^{2}",
    "originalEquation": "(-\\log_{2}(\\sqrt{2}))^{2}",
    "outEquation": "(-\\log_{2}(\\sqrt{2}))^{2}",
    "dymEquation": "(-\\log_{2}(\\sqrt{2}))^{2}",
    "isTemplate": false,
    "showDidYouMean": false,
    "showInstead": false
  }
}

Я получил step_input и whole_result, но у меня были проблемы с полем заголовка и полем объяснения. Итак, код для полей step_input и whole_result

public class Root
{
    public List<Step> solutions { get; set; }

    public class Step
    {
        public string step_input { get; set; }
        public string entire_result { get; set; }
        // rest of properties
        public List<Step> steps { get; set; }
    }
}
var dynObj = JsonConvert.DeserializeObject<Root>(NotParsedResponse); // json above
foreach (var step in dynObj.solutions)
{
    if (step.steps != null)
    {
        foreach(var step1 in step.steps)
        {
            Result +=  step1.step_input + @" \\ " + step1.entire_result + @" \\ " ;
        }
    }
}

Поэтому я хочу получить поля title и general_rule. Когда я попытался получить его с моим кодом выше, он не работает.

1 Ответ

0 голосов
/ 16 апреля 2020

Вам немного сложно помочь, потому что;

  1. Вы не сообщаете об ошибке
  2. В вашем классе Root пропущены свойства, которые могут быть критическими! !

Однако, если у вас нет правильной настройки вашего Root класса, вам нужно добавить следующее

Добавить тип GeneralRule в Root Добавьте новые классы GeneralRule и MyText

    public class Root
    {
        public List<Step> solutions { get; set; }

        public class Step
        {
            public string step_input { get; set; }
            public string entire_result { get; set; }

            //New entity below
            public GeneralRule general_rule { get; set; }
            public List<Step> steps { get; set; }
        }

        public class GeneralRule
        {
            public MyText text { get; set; }
        }

        public class MyText
        {
            public string createdText { get; set; }
        }
    }

Тогда ваш код должен быть в порядке.

В будущем я предлагаю использовать такой инструмент, как http://json2csharp.com/ чтобы сопоставить ваши JSON направо C# классов. Или используйте параметр Visual Studio Edit-> Paste Special-> Past JSON как классы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...