Learning the process of reading a JSON file from a folder in an ASP.NET project

In the Script folder, I created a subfolder called "js" where I stored a file named json containing an array of cities. I attempted to read this file from the folder and return a list to display in my select view.

{
  "city": [
    { "Name": "Chicago" },
    { "Name": "New York" },
    { "Name": "Los Angeles" },
    { "Name": "Miami" },
    { "Name": "Dallas" },
    { "Name": "Seattle" },
    { "Name": "Boston" }
  ]
}

This is the structure of my classes:

public class City {
  public string Name {
    get;
    set;
  }
}

public class Cities {
  public IList < City > cities {
    get;
    set;
  }
}

Below is the action being executed:

public class CityAction {
  public string GetName() {
    // logic here
  }
  
  public List<string> GetAllCities() {
    // logic here
  }
}

An issue has been identified:

Answer №1

This snippet of code specifies the file path for a json file, not its contents:

  var json = Server.MapPath("~/Scripts/js/cidade.json");

To actually read the contents of the json file, you should modify it like this:

  var json = System.IO.ReadAllText(Server.MapPath("~/Scripts/js/cidade.json"));

Another issue to note is that there is a discrepancy in the property name. Your class has a property IList<Cidade> cidades, but your json file uses the key as cidad

Answer №2

Here is my finalized code snippet:

    [HttpGet]
    public ActionResult Get()
    {
        var json = System.IO.File.ReadAllText(Server.MapPath(@"~/App_Data/cidade.json"));
        City city = JsonConvert.DeserializeObject<City>(json);
        return View(city);

    }

This is the structure of my classes:

    public class Cities
{
    public string Name { get; set; }
}

public class City
{
    public List<Cities> cities { get; set; }
}

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

Fetching the exchanged messages between the sender and recipient - utilizing MongoDB, Express, and React for chat functionality

I am dealing with two collections named students and teachers in the mongodb database. The structure of a conversation between a student and a teacher involves arrays of messages within each object, as well as the IDs of the sender and receiver. I am seeki ...

Tips for resolving Detected package downgrade alerts

I'm currently stuck on a frustrating problem and could really use some fresh ideas. I'm working in Visual Studio 2017 with a .NET Core 1.1 ASP.NET website that utilizes RavenDB. The issue I'm facing is in relation to 4 build warnings that ar ...

Having trouble extracting the video ID from a Youtube feed XML with jQuery

My goal here is quite simple - I have created a search result using a URL string with the YouTube API. When you visit the URL, you can view the XML returned without any issues. The specific URL is: https://gdata.youtube.com/feeds/api/videos?q=all the smal ...

What is the best way to send information from server-side code to an EJS template?

I am facing an issue with retrieving data from my simple server for an ejs template. While I can successfully get the data through the URL in my browser, I am struggling to pass it to the template. This is my data retrieval method: app.get('/some&ap ...

Utilize SQL, PHP, or JavaScript to separate and interpret two JSON strings that have been combined through ws_concat(mysql)

Here's a bit of a challenging question that I'll do my best to simplify. Within my MySQL database, I have the following table/columns: *users* first_name last_name To retrieve these columns in my application, I run an SQL statement like this: ...

Unable to store loop information fetched from api into a JSON file

I'm currently facing an issue with my code where I am trying to save the results from looping through an API into a JSON file using writeFileSync. Here is the code snippet in question: function processRarity(limit) { var resultJson = []; for ( ...

Reveal and Conceal, the ever-changing show

As I work on my blog, I want to make the layout more compact by having a link that reveals comments and entry forms when clicked. I've seen this feature on other sites as "Comments (5)", but I'm unsure how to implement it myself. Below is a snip ...

Is it necessary for me to authenticate jwt tokens?

Let me explain my situation. I have generated a JWT token and stored it in Redis with a TTL of 1 hour. Now, most tutorials suggest using jwt.verify to authenticate the token. I understand that jwt.verify is used to verify whether the token is authentic or ...

Create a basic chart using JavaScript

I am looking to replicate a specific chart using JavaScript. The red point in the chart is variable. So far, I have attempted to create it using the flot library: var d3 = [[7,7]]; $.plot("#placeholder", [{ data: d3, points: { show: true } }], { ...

Saving JSON information to a file through Java

Currently in my Java code, I am making a call to a REST API Get method and I need to save the JSON data retrieved into a file. Below is an example of the JSON data: { "took" : 25, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "fa ...

Identifying asynchronous JavaScript and XML (AJAX) requests using Express in NodeJS

When working with NodeJS and Express, I am wondering how to distinguish between a regular browser request and an AJAX request. I understand that one approach is to inspect the request headers, but I am curious if Node/Express provides direct access to th ...

Unlocking the power of JavaScript/HTML integration in CLR

Is it possible to extract HTML and JavaScript into distinct projects, and then retrieve the code by extracting it from the dll in a different project? Any advice on how to access the code from the dll? This is for distributing modules, specifically in MV ...

Filtering input that is compatible with Firefox

Attempting to restrict certain special characters (excluding "_" and "-") from being used in a text input field has been a bit of a challenge. I initially tried using regex filtering by pattern, but it didn't work as expected. Then I turned to dynami ...

Combining JSON and PHP for seamless integration

I am utilizing the getJson() function to dynamically fetch content from the server using PHP. Here is an example of the code: function loadContent(url){ $.getJSON("content.php", {cid: url, format: 'json'}, function(json) { ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

"Enhance Your Website with Stylish Bootstrap Pop

Hello, I am trying to display a "Loading..." text or spinner image while waiting for the dynamic ajax content to load. Due to the large amount of data that needs to be fetched, it takes approximately 2-3 seconds for the content to fully load. Below is my ...

Transferring session id across various devices using PHP

Here's the scenario: I have two users accessing different pages on separate devices - one user is on page 1 and the other is on page 2. My goal is to implement PHP forms on page 1 that can dynamically change the content displayed on the second user& ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

The value passed to the JavaScript function appears to be null, despite not actually being null

Here are the specific API functions I am using to call from JavaScript: function SuspendActionOp(barcode, owner) { //alert(barcode+" - "+num); alert(owner); if (owner == null) { alert('owner is null'); } else { $.ajax({ url: &apo ...

Using Go to persist JSON logs by creating and validating unique filenames repeatedly

I am relatively new to Go and I find myself regularly receiving a small (~1KB) JSON file from an API that acts as a log. My goal is to preserve each of these files for future reference. Instead of using a database, which seems unnecessary for this task, I ...