Generating a JSON array from a C# collection can be achieved by utilizing the System.Web.Script.Serialization

Can someone help me with this code snippet?

            var httpWebRequestAuthentication = (HttpWebRequest)WebRequest.Create("http://api");
        httpWebRequestAuthentication.ContentType = "application/json";
        httpWebRequestAuthentication.Accept = "en";
        httpWebRequestAuthentication.Headers.Add("Accept-Language", "en");
        httpWebRequestAuthentication.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequestAuthentication.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                agent_name = "my name",
                agent_password = "myPassword",
                countryCode = "US",
                requestType = "post",
                sales_representatives = new[] { // How can I dynamically create a JSON array from a C# collection using a foreach loop?
                new {
                  product = "agent1",
                  primary_sales_representative= 1234,
                  secondary_sales_representative= 2345
                },
                new {
                  product = "agent2",
                  primary_sales_representative = 1111,
                  secondary_sales_representative= 2222
                }
                }
            });

            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponseAuthentication = (HttpWebResponse)httpWebRequestAuthentication.GetResponse();
        using (var streamReaderAuthentication = new StreamReader(httpResponseAuthentication.GetResponseStream()))
        {
            var resultAuthentication = streamReaderAuthentication.ReadToEnd();
        }

I need to modify the code so that my sales_represetatives JSON collection is generated from a C# list of sales representatives.

Is there a way for me to include a foreach loop in this code to achieve this?

Answer №1

Simply swap out that code:

 salespeople = new[] { // Can someone show me how to use a Foreach loop in C# to go through a collection and generate a JSON array?
            new {
              product = "agent1",
              primary_salesperson = 1234,
              secondary_salesperson= 2345
            },
            new {
              product = "agent2",
              primary_salesperson = 1111,
              secondary_salesperson= 2222
            }
            }

With this one instead:

salespeople = yourCollection.Select(person=>new {
  product = person.ProductField,
  primary_salesperson = person.PrimaryField,
  secondary_salesperson = person.SecondaryField
}

This assumes that your list of salespeople in C# is stored in a collection called "yourCollection", and each object in that collection has ProductField, PrimaryField, and SecondaryField properties. Feel free to customize as needed.

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

Exploring the compatibility between ADFS 2.0 and JSONP

My main website uses passive federation (ADFS 2.0) and includes javascript that communicates with an MVC Web API site using jsonp. I am facing a challenge in getting this WebAPI to support Single Sign On on the same machine but different port. The passive ...

Updating a deeply nested value with React's setState

Dealing with a deeply nested object in my React state has been quite the challenge. The task at hand is to modify a value within a child node. Fortunately, I have already identified the path leading to the node that needs updating and I am utilizing helper ...

Issue with Google Script not initializing in a second form

I'm currently working on a project that is bound to a Google Sheet container. The purpose of this project is to search for a specific value in one column, and based on the result, either mark the record as complete, allow for missing values to be fill ...

Develop two varieties of user account models using Mongodb/Mongoose

Currently, I am utilizing mongoose in my nodejs project and I am seeking advice on creating a MongoDB schema that caters to two different user types: employees and clients. Both of these users will be registering through the same page (I am implementing pa ...

CSS: Problem Arising from Line Connections Between Tree Elements

I'm currently working on connecting tree nodes with lines in a drawing. I've managed to achieve it to some extent, but there are a few issues like dangling lines that I need to fix. You can find the implementation on codepen here: https://codepe ...

Formulation, on the other side of the comma

I have a calculation script that is almost working perfectly, but it seems to be ignoring values with decimal points. Can anyone offer some guidance on how to fix this issue? var selects = $('select'); var inputs = $('input'); selects. ...

What is the best way to present JSON data retrieved from an API on different pages using Next.js?

I am currently working on two pages that are connected: one is an API page called secured.js (where user session data is processed) and the other is a normal page also named secured.js (which displays the processed content from the API page). This is the ...

Retrieve elements from an array based on the value of an object

I have a list of items that resembles the following structure: var entries = [ { sys: {id:"1"}, fields: "article1" }, { sys: {id:"2"}, fields: "place1" }, { sys: {id:"3"}, fields: "offer2" }, { sys: {id:"1"}, fields: "article2" }, { sys: {id:"1" ...

Guide on developing API endpoints with Rails and incorporating Swagger documentation for nested resources

In my Rails application, I am utilizing Active Record serializers to handle responses in JSON or HTML for the purpose of creating a public API. For basic authentication, I am using Devise Simple HTTP. To document my APIs, I have incorporated Swagger docs ...

Json representation of HTTP status codes

Up to this point, my approach to building API's has been like the following: @GET @GZIP @Path("/login") @Produces(MediaType.TEXT_HTML) public Response login(@QueryParam("email") String email, @QueryParam("password") String passwor ...

Issue when activating Materialize Bootstrap

I'm facing an issue with my code. I have implemented a feature where a modal should be triggered after a user successfully adds a new user. However, I am using Materialize and the modal is not being triggered. Below is a snippet of my code: <div i ...

I'm curious about the origin and purpose of req.user - where does it come from and

Recently, I've been delving into Nestjs and found myself a bit puzzled by the req.user. Where does this come from and do we have to manually request it? What exactly is req.user and what advantages does it offer? Must I assign payload to it manually? ...

How can I access Google's description using JSON?

Currently, I have code that utilizes Google API calls to return the title and URL. However, I am looking to extract the description of a LinkedIn page and split the information by ';'. Is there a command available for this? I have found commands ...

I'm struggling to figure out how to distinguish between a file and a directory in my treeView1

Here is the process for adding nodes to the TreeNode: private int total_dirs; private int searched_until_now_dirs; private int max_percentage; private TreeNode directories_real_time; private string SummaryText; pri ...

Ways to insert text at the start and end of JSON data in order to convert it into JSONP format

Currently, I am working on a project where I need to add a prefix "bio(" and a suffix ")" to my JSON data in order to make it callable as JSONP manually. I have around 200 files that require this modification, which is why I am looking for a programmatic ...

Setting a default value in Vue props if it doesn't pass validation: A guide

Is it possible to assign a default value to a prop using a validator? For instance, if the current prop does not pass the validator and is less than 3, I would like to automatically set the value to 1. Here's an example: currentStep: { type ...

Tips for transforming the appearance of an asp.net page with asp:Content into a stylish css-page

Currently facing an issue where I am unable to change the background-color in my CSS file. As a workaround, I have placed the style directly within an ASP page. <asp:Content Id="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

What is the best way to retrieve the canonicalized minimum and maximum values within the beforeShow method of jQuery UI's datepicker?

I have a pair of datepicker elements that I want to function as a range. When a value is set in the "low" datepicker, it should adjust the minDate and yearRange in the other datepicker, and vice versa with the "high" datepicker. The challenge I'm faci ...

Attempting to program a bot to navigate in a random pattern across a two-dimensional xz plane using Threejs

My journey began with the code below, which initiates a block moving in a straight line: const bot_geometry = new THREE.BoxGeometry(1,1,1); const bot_material = new THREE.MeshBasicMaterial( {color: 0x7777ff, wireframe: false} ); const bot = new THREE.Me ...