Showing formatted JSON in the view using ASP.NET MVC

Is there a method to modify JSON for presentation in the interface? I am looking for a way to automatically update my API documentation when adding new properties. It would be great if I could also apply CSS styling to certain elements. This feature is something I am interested in for XML as well.

class Student 
{
      static CreateEmpty()
      {
           return new Student() {
                 FirstName: 'Mike',
                 LastName: 'Flynn',
                 Classes: new List<Class>(),
                 School: new School() {
                      Name: 'High School'
                 }
           }
      }
}


<code>
@(Student.CreateEmpty().ToJSON())
</code>

to

<code>

{
     FirstName: 'Mike',
     LastName: 'Flynn',
     Classes: [],
     School: {
          Name: 'High School'
     }
}

</code>

Answer №1

If you are looking to customize the JSON format and add indentation, consider using JSON.NET:

<pre>@Html.Raw(JsonConvert.SerializeObject(Student.CreateEmpty(), Formatting.Indented))</pre>

Answer №2

Here is an alternative method that utilizes Newtonsoft. Remember to include the pre html tag for proper formatting.

<pre>
@Html.Raw(Newtonsoft.Json.Linq.JValue.Parse(Student.CreateEmpty()).ToString(Newtonsoft.Json.Formatting.Indented)
</pre>

Answer №3

My approach involves directly formatting HTML (primarily for debugging purposes), though it can be enhanced to add more sophistication.

    public static void FormatJSONObject(object obj, StringBuilder sb, int indent)
    {
        if(obj.GetType() == typeof(System.Object[]))
        {
            sb.AppendLine("[<br>");
            int index = 0;
            foreach(object item in (object[])obj)
            {
                sb.Append("<b><i>" + index + "</i></b><br><div style='padding-left: " + indent +
                          "em;'>");
                FormatJSONObject(item, sb, indent + 2);
                sb.AppendLine("</div>");
                index++;
            }
            sb.AppendLine("]<br>");
        }
        else if(obj.GetType() == typeof(Dictionary<string, object>))
        {
            sb.AppendLine("{<br><div style='padding-left: " + indent + "em;'>");
            foreach (var pair in (Dictionary<string, object>)obj)
            {
                sb.Append("<b>");
                sb.Append(pair.Key);
                sb.Append("</b>&nbsp;:&nbsp;");
                FormatJSONObject(pair.Value, sb, indent + 2);
            }
            sb.AppendLine("</div>}<br>");
        }
        else
        {
            sb.Append(obj.ToString());
            sb.AppendLine("<br>");
        }
    }

This function is then called within the button click handler on the ASP server side...

    protected  void ProcessButtonClick(object sender, EventArgs e)
    {
        RegisterAsyncTask(new PageAsyncTask(LoadTestData));
    }

    public async Task LoadTestData()
    {
        using (HttpClient client = new HttpClient())
        {
            // Example URL: "http://jsonplaceholder.typicode.com"
            client.BaseAddress = new Uri(APIURLBase.Text);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
            // Example endpoint: "posts/1"
            HttpResponseMessage response = await client.GetAsync(APIURLRequest.Text);
            if (response.IsSuccessStatusCode)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<H1>Return Status:</H1>&nbsp;" + response.StatusCode.ToString() + "<br>");

                sb.AppendLine("<H1>Headers</H1><br>");
                foreach (var header in response.Headers)
                {
                    foreach (var value in header.Value)
                    {
                        sb.AppendLine("<label>" + header.Key + "</label>&nbsp;" + value + "<br>");
                    }
                }

                sb.AppendLine("<H1>Content</H1><br>");
                sb.AppendLine("<label>Content Type: </label>" + Response.ContentType + "<br>");
                Stream memoryStream = new MemoryStream();
                Stream bodyStream = await response.Content.ReadAsStreamAsync();
                bodyStream.CopyTo(memoryStream);
                memoryStream.Position = 0;
                using (StreamReader reader = new StreamReader(memoryStream))
                {
                    string responseBody = reader.ReadToEnd();
                    if (ShowRawContentCB.Checked)
                    {
                        sb.AppendLine(responseBody + "<br>");
                    }
                    else
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        object jsonObj = serializer.Deserialize(responseBody, typeof(object));
                        FormatJSONObject(jsonObj, sb);
                    }
                }

                this.results.InnerHtml = sb.ToString();
            }
            else
            {
                this.results.InnerHtml = "<label>Error:</label>&nbsp;" + response.StatusCode.ToString();
            }

        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unravel the JSON data in each array and convert it into

I have a JSON string encoded like the following: [ {"title":"root", "link":"one"}, {"title":"branch", "link":"two"}, {"title":"leaf", "link":"three"} ] My goal is to decode this JSON and display it in PHP as shown below: title || link r ...

Use JQuery to reverse the most recent button click

Here is the code snippet I am working with: <button class="btn">New York</button> <button class="btn">Amsterdam</button> <button class="btn">New Jersey</button> <button class="btn&qu ...

Troubleshooting Problems with Ruby Arrays, JavaScript, and JSON

I am facing a challenge with rendering a highcharts plugin in my rails application. I suspect it could be related to the sql queries fetching data from the database and converting them into a ruby array that the javascript code fails to interpret correctly ...

Verifying the contents of a variable for a specified string in Python

I am working on processing data from the twitch API to determine whether a channel is live or not. Here is an example of how I'm doing it using a JSON list: import requests import json r = requests.get("http://some-api/api", params) rdata = r.json( ...

Troubleshooting Issues with Retrieving Android Data from MySQL Database using PHP and JSON

Even though I have encountered this question multiple times on stack overflow, I have tried all the solutions provided and none of them seem to work for me. I am attempting to display data in a List View. The data is stored in JSON format and it appears t ...

What are the steps to achieve the desired PrimeFaces theme appearance for selectOneMenu?

Need help with a JSF Primefaces project using the omega theme. The selectOneMenu dropdowns are not displaying correctly (missing line). Current look: https://i.stack.imgur.com/vF4ms.png Expected look: https://i.stack.imgur.com/hXsIB.png Any suggestion ...

Risks associated with storing configuration files in JSON/CPickle are related to security

In search of a secure and flexible solution for storing credentials in a config file for database connections and other private information within a Python module. This module is responsible for logging user activity in the system through different handler ...

Trouble with placing an absolutely positioned element using Tailwindcss

I am currently working on a project using TailwindCSS in which I have a logo positioned to the left and navigation to the right. Both elements are centered, but because the logo has a position of absolute, it appears in front of the navigation. I would lik ...

Looking to create a custom loader that adapts to different screen sizes

Can anyone help me make the text in my centered div responsive on my website loader? I'm new to coding and struggling to figure it out. Any assistance would be greatly appreciated! Make sure to view the full page snippet so you can see the text prope ...

What is the best approach to animating a specified quantity of divs with CSS and javascript?

How neat is this code snippet: <div class="container"> <div class="box fade-in one"> look at me fade in </div> <div class="box fade-in two"> Oh hi! i can fade too! </div> <div class="box fade-in three"& ...

When attempting to execute the 'npm start' command, an error was encountered stating "start" script is

Encountering an issue when running "npm start." Other users have addressed similar problems by adjusting the package.json file, so I made modifications on mine: "scripts": { "start": "node app.js" }, However, t ...

Modal window displaying MVC 4 partial view

I've been attempting to display a partial view using a popup, but it's not working. The controller method is also not being triggered. Here's my code: Script:- $(document).ready(function () { $.ajaxSetup({ cache: false }); ...

Using media queries in VueJS style tags may not have the desired effect

I've encountered an issue with using @media in the style tags of a VueJS component. Surprisingly, styling within the @media query works consistently, while applying styles based on width rules does not seem to have any effect. <template> &l ...

Issue with horizontal scrolling in ng-scrollbars occurs when scrolling from right to left

We are currently developing a single page application that supports two languages, one being right to left and the other left to right. For scrolling functionality, we have implemented ng-scrollbars, an Angularjs wrapper for the malihu-custom-scrollbar-pl ...

Having trouble with the clear button for text input in Javascript when using Bootstrap and adding custom CSS. Any suggestions on how to fix

My code was working perfectly until I decided to add some CSS to it. You can view the code snippet by clicking on this link (I couldn't include it here due to issues with the code editor): View Gist code snippet here The code is based on Bootstrap. ...

`How to Customize Page Titles and Add Content in WooCommerce`

Currently, I am facing a challenge in adding content after the page title and changing the style of the page where all products are displayed in WooCommerce. Unfortunately, I am unsure about the location of the file that needs to be copied to my custom t ...

Could we customize the appearance of the saved input field data dropdown?

I'm currently working on styling a form that includes an input field. The challenge I'm facing is that the input field needs to be completely transparent. Everything works fine with the input field until I start typing, which triggers the browser ...

One-of-a-kind Version: "Utilizing CSS to Capitalize an

Imagine having the following strings. i and we. me and you. he and she. Is it possible to achieve the desired result using PURE CSS? I and We. Me and You. He and She. If capitalizing the text using text-transform: capitalize is used, it will yi ...

What is the most efficient method for storing and retrieving numerous DOM elements as JSON using the FileSystem (fs) Module in Node.js?

Is there a way to efficiently save dynamically added DOM elements, such as draggable DIVs, to a file and then reload them later on? I am looking for the most organized approach to achieve this. ...

Update the appearance of a cell if the value within it is equal to zero

I have discovered a way to achieve this using inputs. input[value="0"] { background-color:#F7ECEC; color:#f00;} Now, I am looking for assistance in applying the same concept to table cells. Can anyone provide guidance? Thank you. ...