Read json output with json.net (c#)

I have this json output.
var jsonstr = "{\"formattedResults\":{\"ruleResults\":{\"MinimizeRenderBlockingResources\":{\"localizedRuleName\":\"Eliminate render-blocking JavaScript and CSS in above-the-fold content\",\"ruleImpact\":12.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]},\"urlBlocks\":[{\"header\":{\"format\":\"None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.\"}},{\"header\":{\"format\":\"{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/BlockingJS\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 1 output\"}]}}]},{\"header\":{\"format\":\"{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 2 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 3 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 4 output\"}]}}]}]},\"PrioritizeVisibleContent\":{\"localizedRuleName\":\"Prioritize visible content\",\"ruleImpact\":.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent\"}]}}}}}";
dynamic json = JsonConvert.DeserializeObject<dynamic>(jsonstr);
foreach (var item in json.formattedResults.ruleResults)
{
	Response.Write(item.Name+"<br>");
}

Open in new window

But I want this outpub. How does I crawl the json string to get the output? Does anybody know?
MinimizeRenderBlockingResources:
(Eliminate render-blocking JavaScript and CSS in above-the-fold content)
value 1 output
value 2 output
value 3 output
value 4 output

PrioritizeVisibleContent:
(Prioritize visible content)
Jesper ChristensenProgrammerAsked:
Who is Participating?
 
it_saigeDeveloperCommented:
Here is how you could do it:
using System;

namespace EE_Q29073719
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonstr = "{\"formattedResults\":{\"ruleResults\":{\"MinimizeRenderBlockingResources\":{\"localizedRuleName\":\"Eliminate render-blocking JavaScript and CSS in above-the-fold content\",\"ruleImpact\":12.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]},\"urlBlocks\":[{\"header\":{\"format\":\"None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.\"}},{\"header\":{\"format\":\"{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/BlockingJS\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 1 output\"}]}}]},{\"header\":{\"format\":\"{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 2 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 3 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 4 output\"}]}}]}]},\"PrioritizeVisibleContent\":{\"localizedRuleName\":\"Prioritize visible content\",\"ruleImpact\":.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent\"}]}}}}}";
            dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonstr);
            foreach (var item in json.formattedResults.ruleResults)
            {
                Console.WriteLine(item.Name);
            }

            if (json?.formattedResults?.ruleResults?.MinimizeRenderBlockingResources?.urlBlocks != null)
            {
                foreach (var urlBlock in json.formattedResults.ruleResults.MinimizeRenderBlockingResources.urlBlocks)
                {
                    if (urlBlock.urls != null)
                    {
                        foreach (var url in urlBlock.urls)
                        {
                            if (url?.result?.args?[0]?.value != null)
                            {
                                Console.WriteLine(url.result.args[0].value);
                            }
                        }
                    }
                }
            }
            Console.ReadLine();
        }
    }
}

Open in new window

Which produces the following output -Capture.PNG
A better solution, however, would be to create distinct objects and map your json to those objects; e.g. -
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q29073719
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonstr = "{\"formattedResults\":{\"ruleResults\":{\"MinimizeRenderBlockingResources\":{\"localizedRuleName\":\"Eliminate render-blocking JavaScript and CSS in above-the-fold content\",\"ruleImpact\":12.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]},\"urlBlocks\":[{\"header\":{\"format\":\"None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.\"}},{\"header\":{\"format\":\"{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/BlockingJS\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 1 output\"}]}}]},{\"header\":{\"format\":\"{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 2 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 3 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 4 output\"}]}}]}]},\"PrioritizeVisibleContent\":{\"localizedRuleName\":\"Prioritize visible content\",\"ruleImpact\":.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent\"}]}}}}}";
            Root json = JsonConvert.DeserializeObject<Root>(jsonstr);
            if (json?.formattedResults?.ruleResults != null)
            {
                foreach(var property in typeof(RuleResults).GetProperties())
                {
                    Console.WriteLine(property.Name);
                }

                Console.WriteLine(string.Join("\r\n", (from urlBlock in json.formattedResults.ruleResults.MinimizeRenderBlockingResources.urlBlocks
                                                       where urlBlock?.urls != null
                                                       from url in urlBlock.urls
                                                       where url?.result?.args?[0]?.value != null
                                                       select url.result.args[0].value)));
            }
            Console.ReadLine();
        }
    }

    class Root
    {
        public FormattedResults formattedResults { get; set; }
    }

    class FormattedResults
    {
        public RuleResults ruleResults { get; set; }
    }

    class RuleResults
    {
        public MinimizeRenderBlockingResources MinimizeRenderBlockingResources { get; set; }
        public PrioritizeVisibleContent PrioritizeVisibleContent { get; set; }
    }

    public class MinimizeRenderBlockingResources
    {
        public string localizedRuleName { get; set; }
        public double ruleImpact { get; set; }
        public List<string> groups { get; set; }
        public Summary summary { get; set; }
        public List<UrlBlock> urlBlocks { get; set; }
    }

    public class PrioritizeVisibleContent
    {
        public string localizedRuleName { get; set; }
        public double ruleImpact { get; set; }
        public List<string> groups { get; set; }
        public Summary summary { get; set; }
    }

    public class Summary
    {
        public string format { get; set; }
        public List<Argument> args { get; set; }
    }

    public class Argument
    {
        public string type { get; set; }
        public string key { get; set; }
        public string value { get; set; }
    }

    public class UrlBlock
    {
        public Arguments header { get; set; }
        public List<Url> urls { get; set; }
    }

    public class Url
    {
        public Arguments result { get; set; }
    }

    public class Arguments
    {
        public string format { get; set; }
        public List<Argument> args { get; set; }
    }
}

Open in new window

Which produces the same output as above.

-saige-
0
 
Ryan ChongCommented:
sorry, what output you want to retrieve here?

as you got json below:

{
  "ruleResults": {
    "MinimizeRenderBlockingResources": {
      "localizedRuleName": "Eliminate render-blocking JavaScript and CSS in above-the-fold content",
      "ruleImpact": 12.0,
      "groups": [
        "SPEED"
      ],
      "summary": {
        "format": "Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.",
        "args": [
          {
            "type": "INT_LITERAL",
            "key": "NUM_SCRIPTS",
            "value": "1"
          },
          {
            "type": "INT_LITERAL",
            "key": "NUM_CSS",
            "value": "3"
          }
        ]
      },
      "urlBlocks": [
        {
          "header": {
            "format": "None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML."
          }
        },
        {
          "header": {
            "format": "{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:",
            "args": [
              {
                "type": "HYPERLINK",
                "key": "LINK",
                "value": "https://developers.google.com/speed/docs/insights/BlockingJS"
              }
            ]
          },
          "urls": [
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 1 output"
                  }
                ]
              }
            }
          ]
        },
        {
          "header": {
            "format": "{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:",
            "args": [
              {
                "type": "HYPERLINK",
                "key": "LINK",
                "value": "https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery"
              }
            ]
          },
          "urls": [
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 2 output"
                  }
                ]
              }
            },
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 3 output"
                  }
                ]
              }
            },
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 4 output"
                  }
                ]
              }
            }
          ]
        }
      ]
    },
    "PrioritizeVisibleContent": {
      "localizedRuleName": "Prioritize visible content",
      "ruleImpact": 0.0,
      "groups": [
        "SPEED"
      ],
      "summary": {
        "format": "You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.",
        "args": [
          {
            "type": "HYPERLINK",
            "key": "LINK",
            "value": "https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent"
          }
        ]
      }
    }
  }
}

Open in new window

0
 
Ganesh GuruduSenior ConsultantCommented:
Hello Christensen,

it seem your are doing wrong, is the code working? definitely it might have error.

it always work on name value pairs.

you may get output like this
localizedRuleName : Eliminate render-blocking JavaScript and CSS in above-the-fold content
ruleImpact: 12.0
groups:[SPEED]
summary:{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]}
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Ganesh GuruduSenior ConsultantCommented:
0
 
Jesper ChristensenProgrammerAuthor Commented:
Hi guys.

Thanks for your reply.

Maybe I did not make myself clear

if I run my code, I get this output:
MinimizeRenderBlockingResources
PrioritizeVisibleContent

Bud I would like this output:
MinimizeRenderBlockingResources:
(Eliminate render-blocking JavaScript and CSS in above-the-fold content)
value 1 output
value 2 output
value 3 output
value 4 output

I can´t figure out how to loop through the json objects.
0
 
Ganesh GuruduSenior ConsultantCommented:
try using below code

Response.Write(item.Name+"<br>");

you need get into sub level like this. or use sub loop

foreach (var item in json.formattedResults.ruleResults.MinimizeRenderBlockingResources)
{
      Response.Write(item.Name+"<br>");
}
OR  like this

Response.Write(json.formattedResults.ruleResults(item).localizedRuleName+"<br>");
0
 
Jesper ChristensenProgrammerAuthor Commented:
Hi. Try insert my code to VS Studio? Then you will se, that your code returns the same as mine.

 
How do I loop through the json string and get the values I want? F.ex:
value 1 output
value 2 output
value 3 output
value 4 output
0
 
Ryan ChongCommented:
How do I loop through the json string and get the values I want? F.ex:
value 1 output
value 2 output
value 3 output
value 4 output
still not clear what do you mean by value 1 output? can you give a real example from your json value?
0
 
Jesper ChristensenProgrammerAuthor Commented:
Saige THANKS !!!!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.