Parsing JSON data from a stream

I have been working with an API lately that provides data in JSON format, and I know the fields it contains. I am trying to deserialize this data into a list format. I checked out the Newtonsoft.Json namespace for help, but unfortunately, the article I came across didn't quite address my specific issue since I am not familiar with the key/value pairs used. You can find the article here: http://www.newtonsoft.com/json/help/html/deserializeobject.htm

Here is a snippet of my code:

static void GetShares()
{
    WebRequest request = WebRequest.Create("https://shares.ppe.datatransfer.microsoft.com/api/v1/data/shares/");

    request.Method = "GET";
    request.Headers.Add("Authorization","Basic "+
    Convert.ToBase64String(
    Encoding.ASCII.GetBytes("useridandpassword")));
    request.ContentType = "application/json";
    WebResponse response = request.GetResponse();
    Stream dataStream = response.GetResponseStream();

    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(dataStream);

    // Read the content.
    string responseFromServer = reader.ReadToEnd();

    Console.WriteLine(responseFromServer);
}

Answer №1

After running the code provided, the console output is displaying data in a non-indented format as shown below:

[
  {
    "browse_count": 0,
    "bytes_free_string": null,
    "bytes_total_string": null,
    "bytes_unknown": true,
    "comment_added_at": null,
    "content_added_at": null,
    "created_at": "2016-06-09T17:23:53-07:00",
    "directory": "/",
    "error_bytes_free_size": null,
    "error_percent_free": null,
    "home_share": false,
    "id": 63,
    "name": "linuxServerRoot",
    "node_id": 5,
    "percent_free": null,
    "status": null,
    "status_at": "2016-12-06T21:24:26-08:00",
    "status_message": null,
    "updated_at": "2016-12-06T21:24:26-08:00",
    "warn_bytes_free_size": null,
    "warn_percent_free": null
  },
  // more JSON data here...
]

In order to display this JSON data in a readable format on the console, you need to deserialize it. To achieve this, you can utilize the Newtonsoft.Json library by adding the Json.NET NuGet package to your project and including the following code snippet before the

Console.WriteLine(responseFromServer);
statement:

JToken jsonToken = JToken.Parse(responseFromServer);
responseFromServer = jsonToken.ToString(Newtonsoft.Json.Formatting.Indented);

By implementing the above code, the JSON data will be formatted and displayed in a readable manner on the console window.

Answer №2

Here is the solution:

WebRequest request = WebRequest.Create("https://shares.ppe.datatransfer.microsoft.com/api/v1/data/shares/");

request.Method = "GET";
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(
Encoding.ASCII.GetBytes("username:password")));
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();

// Use StreamReader to read stream easily.
StreamReader reader = new StreamReader(dataStream);

// Read the content.
string responseFromServer = reader.ReadToEnd();

JArray items = JArray.Parse(responseFromServer);

Console.WriteLine($"{"Property Keys".PadRight(24)}Values");
Console.WriteLine($"{"".PadRight(50, '-')}");

foreach (JToken token in items)
{
    Dictionary<string, string> dictionary = token.ToObject<Dictionary<string, string>>();

    int length = 28;

    foreach (var property in dictionary)
    {
        Console.WriteLine($"{property.Key.PadRight(length)}{property.Value}");
    }

    Console.WriteLine($"----------------------");
}

This code snippet extracts keys from a deserialized JSON array by parsing it into a dictionary and displaying them with proper padding. Adjust the key length padding as needed for optimal display.

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

Python code for performing a surgical replacement of a JSON field with another in a file

Currently, I am dealing with a large collection of JSON files structured like this: File00, timestamp T1: { "AAA": { "BBB": { "000": "value0" }, "CCC": { "111": "value1", "222": "value2", "333": "value3" }, " ...

Tips for automatically incorporating animation upon page initialization

I'm looking to add an automatic image effect when the page is loaded. I currently have this code in my js file: $(window).ready(function(){ $(pin).click(function(){ $("#pin01").show().animate({left: '650px'}); }) }); Here is the HTML wit ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

How to exclude specific properties from JSON serialization in Spring MVC using Jackson?

Issue: I am looking for a simple way to exclude certain class properties (such as fields that should not be publicly exposed without authorization) when an object is returned in the @RestController method. class Article { String title; String c ...

Transform your .obj files into .glb files effortlessly with npm and Laravel

I've hit a roadblock for 2 days now and can't seem to find a solution. Could someone lend me a hand with this? Query: What's the best way to convert a .obj file to .glb? I attempted using obj2gltf npm package but integrating it with Larav ...

Animating slides with CSS Keyframes and React, incorporating toggle slide fade out and slide fade (back) in

I am seeking a solution for toggling a box (div) with slide-out animation and then sliding back in animation (in reverse) upon button press. My requirement is to have no animations during the initial page render. While I can successfully slide the box to ...

Removing elements from an array within a function

Within my class, I defined an array: myUsers = new Array(); I am looking to add usernames to this array in a unique manner. My approach involves checking if the array length is 0 and if so, adding a user. This method works well for adding the first user ...

Continuously make Ajax requests to populate numerous div elements

There are two div elements present on my webpage. <div id="1"></div> <div id="2"></div> I am attempting to dynamically populate these divs using the following php call. <script> var queries = ["SELECT * from table1", "S ...

Refreshing Ajax in a different tab causes the selectize element to become unbound from the editing form in Rails 5

In my Rails 5.1 application, I have multiple views with the main view being the calls index view. In this view, I perform an ajax refresh of partials and use a callback to re-initialize the selectize JS element in the calls/index view as shown below: < ...

JavaScript concatenation of arrays

I am working with two arrays: let num1 = [[1]]; const num2 = [2, [3]]; When I combine these arrays, I create a new array: const numbers = num1.concat(num2); console.log(numbers); // This will result in [[1], 2, [3]] Next, I add a ne ...

Using Ajax and JQuery to show a success message prominently

Currently, I have a fully functional flash system implemented in PHP to display a success message to the user once an entry is created in the database. In one of the forms on my website, there is a select field where users should be able to seamlessly add ...

Issue with Jest: Mocked function not found by Vue Component

I am currently in the process of mocking an ES6 class that is being utilized within my Vue Component: export default class DataUploadApi { // Get uploaded files static async getUploadedFiles() : Promise<Object> { return WebapiBase.ge ...

Transforming nested JSON files into nested jQuery divs

Is it possible to iterate through two JSON files that have a parent-child relationship based on simple ID primary and foreign keys? Can we then display the data in a list of divs with the following characteristics: Hierarchical - child divs should only a ...

The JavaScript and CSS properties are not functioning properly with the HTML text field

I came across this CodePen example by dsholmes and made some modifications: Here Furthermore, I have developed my own form on another CodePen pen: Link The issue I'm facing is related to the placeholders/labels not disappearing when typing in text f ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

Typescript does not produce unused members

Having an issue with the JS code that TypeScript compiler is generating. Here's an example class: // Class export class UserDTO { Id: number; FirstName: string; LastName: string; DateOfBirth: Date; getFullName(): string { ...

NEXT JS - Application renders twice due to rewrites in place

I'm currently working on a NEXT JS project and facing the issue of the app rendering twice! Challenge After implementing rewrites in next.config.js, the app is being rendered twice. Removing the rewrites solves the issue and only renders once. next ...

Tips for sending an object to an action method in ASP.NET Core MVC

One way to pass an object for editing from a view to an Upsert action method is by using Tag-Helpers. Here's an example: In my Index.cshtml file (check out the Edit link below): @foreach (var item in Model) { <tr> ...

Is it possible to combine the existing request parameters with a new parameter in JSP/JSTL/JQuery?

Here is a sample URL: http://127.0.0.1:8080/admin/seller?email=tim%40example.com Below is a snippet of JSP code: <a class="btn btn-primary ${page==pages||pages==0?'disabled':''}" href="?page=${page + 1}">Next</a> I am ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...